Tests for function fwrite().
[gnulib.git] / tests / test-fwrite.c
1 /* Test of fwrite() 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 (fwrite, size_t, (const 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-fwrite.txt";
35
36   /* Test that fwrite() on an unbuffered stream sets errno if someone else
37      closes the stream fd behind the back of stdio.  */
38   {
39     FILE *fp = fopen (filename, "w");
40     char buf[5] = "world";
41     ASSERT (fp != NULL);
42     setvbuf (fp, NULL, _IONBF, 0);
43     ASSERT (close (fileno (fp)) == 0);
44     errno = 0;
45     ASSERT (fwrite (buf, 1, sizeof (buf), fp) == 0);
46     ASSERT (errno == EBADF);
47     ASSERT (ferror (fp));
48     fclose (fp);
49   }
50
51   /* Test that fwrite() on an unbuffered stream sets errno if the stream
52      was constructed with an invalid file descriptor.  */
53   {
54     FILE *fp = fdopen (-1, "w");
55     if (fp != NULL)
56       {
57         char buf[5] = "world";
58         setvbuf (fp, NULL, _IONBF, 0);
59         errno = 0;
60         ASSERT (fwrite (buf, 1, sizeof (buf), fp) == 0);
61         ASSERT (errno == EBADF);
62         ASSERT (ferror (fp));
63         fclose (fp);
64       }
65   }
66   {
67     FILE *fp = fdopen (99, "w");
68     if (fp != NULL)
69       {
70         char buf[5] = "world";
71         setvbuf (fp, NULL, _IONBF, 0);
72         errno = 0;
73         ASSERT (fwrite (buf, 1, sizeof (buf), fp) == 0);
74         ASSERT (errno == EBADF);
75         ASSERT (ferror (fp));
76         fclose (fp);
77       }
78   }
79
80   /* Clean up.  */
81   unlink (filename);
82
83   return 0;
84 }