PDA

View Full Version : fflush() help



frs
07-15-2010, 05:53 PM
Can anyone explain the role of fflush in this code? The output is 0 .. 1 .. 2 til 9. When I remove the fflush, it prints 0 1 2 3 4 5 6 7 8 9 at once after 10 seconds. Why?


#include <stdio.h>
#include <unistd.h>

int main(void)
{
int i=0;
printf("PID = %u\n", getpid());
while(i<10)
{
printf("%d ", i++);
fflush(stdout);
sleep(1);
}
printf("\n");
return 0;
}

kermit
07-15-2010, 07:00 PM
The output on your system is normally buffered. The characters are built up in the buffer, up to a certain limit. This is done for efficiency. If the buffer gets full, it writes to whatever output stream it is pointed to. If a newline is encountered in the buffer, it will typically write to the output stream, even if it is not full. The other way to flush the buffer (i.e., make it write to output), is to use a call to fflush. In the case of your code, every time you go through the loop, when it gets to fflush, even though the buffer is far from being full, and there is no newline, the output gets written to stdout. If you leave the fflush call out, then the numbers sit in the buffer until the final printf at the end of the program, where they are then all printed out at once.