fflush(3)

C library function

Forces an output stream to write the bytes it is holding in memory. Needed before a possible crash or a fork, with no guaranteed effect on stdin.

Synopsis
#include <stdio.h>
int fflush(FILE *stream);

Description

The <stdio.h> streams, such as stdout or a file opened with fopen, collect what you write in a buffer and hand it to the kernel, with write(2), only at certain moments: a \n when stdout is a terminal, a full buffer, the normal end of the program. fflush(stream) hands over whatever is waiting right away. fflush(NULL) does it for every open output stream.

fflush only empties the C library's buffer. Once the bytes have reached the kernel, nothing guarantees they are on the disk yet; that is the job of fsync.

Return value

0 on success. On error, EOF, and errno gives the cause, for example EBADF if the stream is not open for writing.

Pitfalls

  • fflush(stdin) does not clear what was typed on the keyboard. The C standard defines fflush for output streams only, and POSIX extends it only to files on disk. To discard the rest of a typed line, read up to the \n.

  • A crash or an abort does not call fflush for you. Since glibc 2.27, abort ends the process without flushing the streams, as the example shows.

  • A prompt without a \n can stay invisible during a read: with musl, the C library of the Grademe exercise terminal, stdout is not flushed before a scanf. Put fflush(stdout) between the prompt and the read.

  • Flush stdout before a fork: otherwise the pending text is copied into the child and printed twice.

Example

with-fflush.c
#include <stdio.h>#include <stdlib.h>
int main(void){    printf("Saving...");    fflush(stdout);    abort();}

without-fflush.c is the same program without line 7.

Terminal
$ ./without-fflushAborted$ ./with-fflushSaving...Aborted

Without fflush, the message was sitting in the buffer, waiting for the end of its line, and abort made it vanish. The article printf not printing before a crash covers the three buffering modes.

Now write it yourself.