The fflush() function (flush to file) is a function that flushes the contents of any output stream (or update stream) to the corresponding file.
fflush(file);
common problem:
#include <stdio.h> int main() { fprintf(stdout, "This is to stdout. "); fprintf(stderr, "This is to stderr. "); fprintf(stdout, "This is also to stdout. "); }
The result is different from what we expected
This is to stderr. This is to stdout. This is also to stdout.
By default, "stdout" is line feed buffered, while "stderr" is unbuffered.
That is: For "stdout", the content of the output stream is actually stored in the temporary buffer until there is a new line character.
The content is written to the "stdout" file only when the output stream encounters a newline character (or the end of the file).
Note that our program don't have line breaks!
Now, add "fflush()" after writing "stdout" to write the contents to the output file immediately.
#include <stdio.h> int main() { fprintf(stdout, "This is to stdout. "); //Flush the contents of the output stream immediately fflush(stdout); fprintf(stderr, "This is to stderr. "); //No need to flush stderr since it is un-buffered fprintf(stdout, "This is also to stdout. "); //Flush the contents of the output stream immediately fflush(stdout); }
output:
This is to stdout. This is to stderr. This is also to stdout.