Thread: fflush() help

  1. #1
    Registered User
    Join Date
    Jun 2010

    fflush() help

    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());
    	 printf("%d ", i++); 
      return 0;

  2. #2
    ... kermit's Avatar
    Join Date
    Jan 2003
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fflush and fgetc question
    By spank in forum Linux Programming
    Replies: 3
    Last Post: 05-24-2007, 05:39 AM
  2. To fflush, or Not to fflush...
    By bjgough in forum C Programming
    Replies: 32
    Last Post: 08-19-2005, 12:56 AM
  3. When and where to use fflush (stdout)?
    By Micko in forum C Programming
    Replies: 8
    Last Post: 02-18-2005, 11:58 AM
  4. Problems with input and fflush
    By edugarcia in forum Linux Programming
    Replies: 1
    Last Post: 11-24-2004, 01:52 PM
  5. everyone's favorite...fflush
    By BungleSpice in forum C Programming
    Replies: 8
    Last Post: 03-12-2004, 11:53 AM