1 /* Detect write error on a stream.
2 Copyright (C) 2003-2006 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2003.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
24 #include "fwriteerror.h"
30 fwriteerror (FILE *fp)
32 /* State to allow multiple calls to fwriteerror (stdout). */
33 static bool stdout_closed = false;
35 if (fp == stdout && stdout_closed)
39 1. test the error indicator of the stream,
40 2. flush the buffers both in userland and in the kernel, through fclose,
41 testing for error again. */
43 /* Clear errno, so that on non-POSIX systems the caller doesn't see a
44 wrong value of errno when we return -1. */
50 goto close_preserving_errno; /* errno is set here */
51 /* The stream had an error earlier, but its errno was lost. If the
52 error was not temporary, we can get the same errno by writing and
53 flushing one more byte. We can do so because at this point the
54 stream's contents is garbage anyway. */
55 if (fputc ('\0', fp) == EOF)
56 goto close_preserving_errno; /* errno is set here */
58 goto close_preserving_errno; /* errno is set here */
59 /* Give up on errno. */
61 close_preserving_errno:
62 /* There's an error. Nevertheless call fclose(fp), for consistency
63 with the other cases. */
65 int saved_errno = errno;
72 /* If we are closing stdout, don't attempt to do it later again. */
77 return -1; /* errno is set here */
85 /* Name of a file on which writing fails. On systems without /dev/full,
86 you can choose a filename on a full filesystem. */
87 #define UNWRITABLE_FILE "/dev/full"
100 static char dummy[8193];
103 for (i = 0; i < sizeof (sizes) / sizeof (sizes[0]); i++)
105 size_t size = sizes[i];
107 for (j = 0; j < 2; j++)
109 /* Run a test depending on i and j:
110 Write size bytes and then calls fflush if j==1. */
111 FILE *stream = fopen (UNWRITABLE_FILE, "w");
115 fprintf (stderr, "Test %u:%u: could not open file\n", i, j);
119 fwrite (dummy, 347, 1, stream);
120 fwrite (dummy, size - 347, 1, stream);
124 if (fwriteerror (stream) == -1)
127 fprintf (stderr, "Test %u:%u: fwriteerror ok, errno = %d\n",
131 fprintf (stderr, "Test %u:%u: fwriteerror found no error!\n",