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.
#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 definesfflushfor 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
abortdoes not callfflushfor you. Since glibc 2.27,abortends the process without flushing the streams, as the example shows.A prompt without a
\ncan stay invisible during a read: with musl, the C library of the Grademe exercise terminal,stdoutis not flushed before ascanf. Putfflush(stdout)between the prompt and the read.Flush
stdoutbefore afork: otherwise the pending text is copied into the child and printed twice.
Example
#include <stdio.h>#include <stdlib.h>
int main(void){ printf("Saving..."); fflush(stdout); abort();}without-fflush.c is the same program without line 7.
$ ./without-fflushAborted$ ./with-fflushSaving...AbortedWithout 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.