1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Close a stream, with nicer error checking than fclose's.
5 Copyright (C) 1998-2002, 2004, 2006-2011 Free Software Foundation, Inc.
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "close-stream.h"
30 # include "unlocked-io.h"
33 /* Close STREAM. Return 0 if successful, EOF (setting errno)
34 otherwise. A failure might set errno to 0 if the error number
37 A failure with errno set to EPIPE may or may not indicate an error
38 situation worth signaling to the user. See the documentation of the
39 close_stdout_set_ignore_EPIPE function for details.
41 If a program writes *anything* to STREAM, that program should close
42 STREAM and make sure that it succeeds before exiting. Otherwise,
43 suppose that you go to the extreme of checking the return status
44 of every function that does an explicit write to STREAM. The last
45 printf can succeed in writing to the internal stream buffer, and yet
46 the fclose(STREAM) could still fail (due e.g., to a disk full error)
47 when it tries to write out that buffered data. Thus, you would be
48 left with an incomplete output file and the offending program would
49 exit successfully. Even calling fflush is not always sufficient,
50 since some file systems (NFS and CODA) buffer written/flushed data
51 until an actual close call.
53 Besides, it's wasteful to check the return value from every call
54 that writes to STREAM -- just let the internal stream state record
55 the failure. That's what the ferror test is checking below. */
58 close_stream (FILE *stream)
60 const bool some_pending = (__fpending (stream) != 0);
61 const bool prev_fail = (ferror (stream) != 0);
62 const bool fclose_fail = (fclose (stream) != 0);
64 /* Return an error indication if there was a previous failure or if
65 fclose failed, with one exception: ignore an fclose failure if
66 there was no previous error, no data remains to be flushed, and
67 fclose failed with EBADF. That can happen when a program like cp
68 is invoked like this `cp a b >&-' (i.e., with standard output
69 closed) and doesn't generate any output (hence no previous error
70 and nothing to be flushed). */
72 if (prev_fail || (fclose_fail && (some_pending || errno != EBADF)))