Name
fflush
Synopsis
Clears a file buffer
#include <stdio.h> intfflush
( FILE *fp
);
The fflush()
function
empties the I/O buffer of the open file specified by the FILE
pointer argument. If the file was
opened for writing, fflush()
writes the contents of the file. If the file is only opened for
reading, the behavior of fflush()
is not
specified by the standard. Most implementations simply clear the
input buffer. The function returns 0 if successful, or EOF
if an error occurs in writing to the
file.
The argument passed to fflush()
may be a
null pointer. In this case, fflush()
flushes the
output buffers of all the program’s open streams. The fflush()
function does not close the file,
and has no effect at all on unbuffered files (see “Files” in Chapter 13 for more information on
unbuffered input and output).
Example
In the following example, the program fflush.c writes two lines of text to a
file. If the macro FLUSH
is
defined, the program flushes the file output buffer to disk after
each line. If not, only the first output line is explicitly flushed.
Then the program raises a signal to simulate a fatal error, so that
we can observe the effect with and without the second fflush()
call.
/* fflush.c: Tests the effect of flushing output file buffers. */ FILE *fp; #ifdef FLUSH char filename[ ] = "twice.txt"; #else char filename[ ] = "once.txt"; #endif /* FLUSH */ fp = fopen( filename, "w" ); if ( fp == NULL) fprintf( stderr "Failed to open file '%s' to write.\n", filename ); fputs( "Going once ...
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.