Previous Page
Next Page

fflush

Clears a file buffer

#include <stdio.h>
int fflush ( 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 function clears the buffer. The function returns 0 if successful, or EOF if an error occurs in writing to the file.

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 ...\n", fp );
fflush( fp );              // Flush the output unconditionally

fputs( "Going twice ...\n", fp );

#ifdef FLUSH
fflush( fp );              // Now flush only if compiled with '-DFLUSH'
#endif

raise( SIGKILL );          // End the program abruptly.

fputs( "Gone.\n", fp );    // These three lines will never be executed.
fclose( fp );
exit( 0 );

When we compile and test the program, the output looks like this:

$ cc -DFLUSH -o fflushtwice fflush.c
$ ./fflushtwice
Killed
$ cc -o fflushonce fflush.c
$ ./fflushonce
Killed
$ ls -l
-rw-r--r--    1 tony     tony          781 Jul 22 12:36 fflush.c
-rwxr-xr-x    1 tony     tony        12715 Jul 22 12:38 fflushonce
-rwxr-xr-x    1 tony     tony        12747 Jul 22 12:37 fflushtwice
-rw-r--r--    1 tony     tony           15 Jul 22 12:38 once.txt
-rw-r--r--    1 tony     tony           31 Jul 22 12:37 twice.txt

The two cc commands have created two different executables, named fflushonce and fflushtwice, and each version of the program has run and killed itself in the process of generating an output file. The contents of the two output files, once.txt and twice.txt, are different:

$ cat twice.txt
Going once ...
Going twice ...
$ cat once.txt
Going once ...
$

When the fputs( ) call returned, the output string was still in the file buffer, waiting for the operating system to write it to disk. Without the second fflush( ) call, the intervening "kill" signal caused the system to abort the program, closing all its files, before the disk write occurred.

See Also

setbuf( ), setvbuf( )


Previous Page
Next Page