SUMMARY
Because of the way the fflush() function clears the stream buffer,
data may be lost after a failed write. This may become apparent when
setting up a critical error handler for a file that uses stream I/O
[for example, fopen(), fclose(), fwrite(), and so on]. To work around
this situation, turn buffering off [with the setvbuf() function] or
use low-level I/O routines instead [for example, open(), close(),
write(), and so on].
When using stream I/O, input and output is buffered. This can provide
significant performance benefits because data is read and written in
larger "chunks." The file buffer is 512 bytes by default but can be
adjusted with the setvbuf() function.
When fflush() is called, either explicitly or implicitly through
fclose(), the data still in the stream is written to the file by an
implicit call to write(). Once that is done, the current location
pointer is reset to the start of the stream buffer and the buffer's
character count is set to zero. Unfortunately, this occurs whether or
not the write() was successful.
In an environment where a critical error handler has been installed,
the application will usually try to rectify the error (that is,
request that the user close the disk drive door, turn on the printer,
insert a formatted disk, and so on), and then retry the operation. For
example:
IOStatus = FAIL;
while(IOStatus == FAIL)
{
fflush(FilePtr);
IOStatus = CriticalErrorChk();
}
However, the second time fflush() is called, the stream has already
been cleared of data and the data is effectively "lost." Calling
setvbuf() with the mode-parameter of _IONBF eliminates this problem by
unbuffering the stream, but file I/O will be slower.
Note that this fflush() behavior is compatible with the ANSI standard.
As required by ANSI, fflush() does return EOF to indicate there was a
problem with flushing the file.
The Help for fflush() in Microsoft C/C++ versions 7.0 and Visual C++ gives
the following information:
Note: If fflush returns EOF, data may have been lost because of a
failed write. When setting up a critical error handler, it is
safest to turn buffering off with the setvbuf function or to use
low-level I/O routines such as _open, _close, and _write instead of
the stream I/O functions.