0f77dbfce13f201e4b13ab5b333efe8101692543
[gnulib.git] / tests / test-fread.c
1 /* Test of fread() function.
2    Copyright (C) 2011 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 #include <config.h>
19
20 #include <stdio.h>
21
22 #include "signature.h"
23 SIGNATURE_CHECK (fread, size_t, (void *, size_t, size_t, FILE *));
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28
29 #include "macros.h"
30
31 int
32 main (int argc, char **argv)
33 {
34   const char *filename = "test-fread.txt";
35
36   /* Prepare a file.  */
37   {
38     const char text[] = "hello world";
39     int fd = open (filename, O_RDWR | O_CREAT | O_TRUNC, 0600);
40     ASSERT (fd >= 0);
41     ASSERT (write (fd, text, sizeof (text)) == sizeof (text));
42     ASSERT (close (fd) == 0);
43   }
44
45   /* Test that fread() sets errno if someone else closes the stream
46      fd behind the back of stdio.  */
47   {
48     FILE *fp = fopen (filename, "r");
49     char buf[5];
50     ASSERT (fp != NULL);
51     ASSERT (close (fileno (fp)) == 0);
52     errno = 0;
53     ASSERT (fread (buf, 1, sizeof (buf), fp) == 0);
54     ASSERT (errno == EBADF);
55     ASSERT (ferror (fp));
56     fclose (fp);
57   }
58
59   /* Test that fread() sets errno if the stream was constructed with
60      an invalid file descriptor.  */
61   {
62     FILE *fp = fdopen (-1, "r");
63     if (fp != NULL)
64       {
65         char buf[1];
66         errno = 0;
67         ASSERT (fread (buf, 1, 1, fp) == 0);
68         ASSERT (errno == EBADF);
69         ASSERT (ferror (fp));
70         fclose (fp);
71       }
72   }
73   {
74     FILE *fp = fdopen (99, "r");
75     if (fp != NULL)
76       {
77         char buf[1];
78         errno = 0;
79         ASSERT (fread (buf, 1, 1, fp) == 0);
80         ASSERT (errno == EBADF);
81         ASSERT (ferror (fp));
82         fclose (fp);
83       }
84   }
85
86   /* Clean up.  */
87   unlink (filename);
88
89   return 0;
90 }