Originally Posted by
blob84
please can you post an example of how fflush works?
As the book says and you says "fflush writes stuff to streams", it is not true, it doesn't print nothing to the stream, if for stream you mean the file or stdout.
Ok... when working with disk files or networks the output stream is buffered in memory, allowing you to accumulate data in memory (which is much faster) then it is written to your device when a) the buffer is near full, b) a reasonable amoutn of time passes, c) the output stream is closed or d) fflush is called.
An example (note error checks omitted for clarity) ...
Code:
FILE* f = fopen("log.txt","w");
// do a mess of stuff
// write a log entry
fprintf(f,"%s %s",time,message);
fflush(f);
// do other stuff
// write another log entry
fclose(f);
Since something like a log file is going to be open for the duration of the program we use fflush() to guarantee that messages are printed to the disk. In an I/O application (modem etc) fflush() ensures the data is sent.
You know that little appy for "safely remove hardware" on the windows task bar... it essentially does fflush() on flash drives, to ensure data is written before we pull the plug on them...