INF: Data May Be Lost During fflush() If Write Is Unsuccessful

ID Number: Q70784

5.10 6.00 6.00a 6.00ax | 5.10 6.00 6.00a

MS-DOS | OS/2

In Microsoft C versions 5.0, 5.1, 6.0, 6.0a, and 6.0ax, 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].

More Information:

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.

The FILE type is used when working with streams. The following is the

current FILE typedef from STDIO.H:

struct _iobuf {

char _FAR_ *_ptr;

int _cnt;

char _FAR_ *_base;

char _flag;

char _file;

};

typedef struct _iobuf FILE;

The fields of the _iobuf are as follows:

_ptr - A pointer to the current location in the stream buffer

_cnt - The number of characters in the buffer

_base - A pointer to the start of the stream buffer

_flag - Various flags to indicate various conditions for the file,

such as current direction (read/write), current

translation mode (binary/text), and so on

_file - The actual file handle

When fflush() is called [either directly or indirectly through

fclose()], the data still in the stream is written to the file [using

write()]. Once that is done, the current location pointer is reset to

the base pointer and the character count is set to zero. The problem

is that 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.

This situation exists with the fflush() function in the C run-time

libraries shipped with C versions 5.0, 5.1, 6.0, 6.0a, and 6.0ax and

QuickC versions 2.0, 2.01, 2.5, and 2.51.

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.