- int e1; /* Leave errno unchanged on success. */
- int e2; /* Capture errno of first fflush if nothing else succeeds. */
- int result;
-
- /* Try flushing the stream. C89 guarantees behavior of output
- streams, so we only need to worry if failure might have been on
- an input stream. When stream is NULL, POSIX only requires
- flushing of output streams. */
- e1 = errno;
- result = fflush (stream);
- if (! stream || result == 0 || errno != EBADF)
- return result;
-
- /* POSIX does not specify behavior for non-seekable streams. */
- e2 = errno;
- if (fseeko (stream, 0, SEEK_CUR) != 0)
- {
- errno = e2;
- return EOF;
- }
+ /* When stream is NULL, POSIX and C99 only require flushing of "output
+ streams and update streams in which the most recent operation was not
+ input", and all implementations do this.
+
+ When stream is "an output stream or an update stream in which the most
+ recent operation was not input", POSIX and C99 requires that fflush
+ writes out any buffered data, and all implementations do this.
+
+ When stream is, however, an input stream or an update stream in
+ which the most recent operation was input, C99 specifies nothing,
+ and POSIX only specifies behavior if the stream is seekable.
+ mingw, in particular, drops the input buffer, leaving the file
+ descriptor positioned at the end of the input buffer. I.e. ftell
+ (stream) is lost. We don't want to call the implementation's
+ fflush in this case.
+
+ We test ! freading (stream) here, rather than fwriting (stream), because
+ what we need to know is whether the stream holds a "read buffer", and on
+ mingw this is indicated by _IOREAD, regardless of _IOWRT. */
+ if (stream == NULL || ! freading (stream))
+ return fflush (stream);
+
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */