0

In cpp reference, it claims fflush is:

Causes the output file stream to be synchronized with the actual contents of the file.

Indeed, I don't understand what it means. I just wonder, in that code, if I take out fflush, is there any difference?

I tested it, it seems there is a little bit difference, but I can't find the pattern. Could any one explain it in details for me? Thanks in advance.

#include<stdio.h>
int i;

int main()
{
    fork();
    for(i=0;i<1000;i++)
    {
        printf("%d\n",i);
        fflush(stdout);// without fflush, is there any difference?
    }
}
Sayakiss
  • 6,403
  • 6
  • 48
  • 94
  • @xaxxon in cpp reference, there are documentations about C. – Sayakiss May 22 '13 at 02:19
  • Deleted comment. I didn't look, I just saw the url.. Your answer is here. Flagging as dupe: http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – xaxxon May 22 '13 at 02:19
  • google for stack overflow printf fflush <== first result – xaxxon May 22 '13 at 02:22
  • I can learn almost everything from google... I think it may be good for me to ask a quick question in SO – Sayakiss May 22 '13 at 02:25
  • The point being the question is repeatedly answered on stack overflow already, you just didn't look. – xaxxon May 22 '13 at 02:26
  • I think it's multithreading lead the difference between fflush and non-fflush. – Sayakiss May 22 '13 at 02:32
  • that doesn't make any sense. multithreading has nothing to do with calling fflush – xaxxon May 22 '13 at 03:11

1 Answers1

3

The standard output is normally flushed when you write a newline. If you want to test this properly, open a file and write to it. For your tests to be useful, you will have to write a lot more data than just a few integers. You should find that omitting fflush will result in significantly faster code. Try timing these two loops...

With flushing:

FILE * fp = fopen("scratch", "w");
for( int i = 0; i < 1000000; i++ ) {
    fprintf( fp, "Hello world" );
    fflush(fp);
}
fclose(fp);

Without flushing:

FILE * fp = fopen("scratch", "w");
for( int i = 0; i < 1000000; i++ ) {
    fprintf( fp, "Hello world" );
}
fclose(fp);

On my machine, the results are:

With fflush:    4.57 seconds
Without fflush: 0.24 seconds
paddy
  • 52,396
  • 6
  • 51
  • 93
  • yeah, there's about a metric ton of answers to this question on SO. – xaxxon May 22 '13 at 02:21
  • But that is quite strange, if fflush will take much time to execute it, so what is fflush usage? – Sayakiss May 22 '13 at 02:27
  • The whole point of `fflush` is to force the output buffer to be written to disk. This is what "synchronised" means. The reason we buffer is because disks are slow and the smallest unit of data that can be written is a sector (traditionally 512 bytes). Sometimes you don't care, and require assurance that everything you output is on the disk. – paddy May 22 '13 at 02:30