Like Tree1Likes
  • 1 Post By Salem

fflush function

This is a discussion on fflush function within the C Programming forums, part of the General Programming Boards category; Hi, what exactly do the fflush function? I found this example here Help - IBM Rational Developer for Power Systems ...

  1. #1
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46

    fflush function

    Hi, what exactly do the fflush function?
    I found this example here Help - IBM Rational Developer for Power Systems Software

    Code:
    #include <stdio.h>
     
    int main(void)
    {
       FILE *stream;
       int ch;
       unsigned int result = 0;
     
       stream = fopen("file", "r");
       while ((ch = getc(stream)) != EOF && isdigit(ch))
          result = result * 10 + ch - '0';
       if (ch != EOF)
          ungetc(ch,stream);
     
       fflush(stream);           /* fflush undoes the effect of ungetc function
    */
       printf("The result is: %d\n", result);
       if ((ch = getc(stream)) != EOF)
          printf("The character is: %c\n", ch);
    }
    It always print the character given by ungetc, so what is the meaning of this?

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,625
    fflush writes stuff to streams, just like the manual says. The example is contrived so that you see definitely how fflush intends to work. Since output streams are flushed when they are closed, and also at other convenient times, such as when an '\n' is encountered in line-buffered streams like stdout, you shouldn't need to call it very often.

  3. #3
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,648
    Important note: this function is not guaranteed to work with input streams in any other compiler, because this:

    If the stream is open for input, the fflush() function undoes the effect of any ungetc() function. The stream remains open after the call.
    is unique to this particular compiler. The result of using fflush() on input streams per the C standard is undefined, meaning that it will do whatever the compiler's creators decided it should do. In this case, IBM gave it a specific and defined action.
    Last edited by rags_to_riches; 06-13-2011 at 06:35 AM.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,422
    You should read what the actual ANSI/ISO standard says
    Quote Originally Posted by C99 Draft
    7.19.5.2 The fflush function
    Synopsis
    1
    #include <stdio.h>
    int fflush(FILE *stream);
    Description
    2 If stream points to an output stream or an update stream in which the most recent
    operation was not input, the fflush function causes any unwritten data for that stream
    to be delivered to the host environment to be written to the file; otherwise, the behavior is
    undefined.
    3 If stream is a null pointer, the fflush function performs this flushing action on all
    streams for which the behavior is defined above.
    Which means that for this part of your link
    Quote Originally Posted by IBM's hacked version
    If the stream is open for input, the fflush() function undoes the effect of any ungetc() function. The stream remains open after the call.
    You NEED to be using the library associated with that documentation.

    If you're using any other LibC, you're in the weeds.
    rags_to_riches likes this.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46
    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.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by blob84 View Post
    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...

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Here's a dead simple example:

    Code:
    #include <stdio.h>
    #include <unistd.h> // caveat
    
    int main(int argc, const char *argv[]) {
    	printf("Hello world");
    	//fflush(stdout);
    	sleep(3);
    
    	return 0;
    }
    First, the "caveat" about unistd.h is that sleep() is actually not a standard C function, but it does exists on most systems. However, the header include will differ. Also: on *nix the parameter is seconds, on windows it is milliseconds. So on windows, use "#include <windows.h>" and change "sleep(3)" to "sleep(3000)".

    Whether this works or not depends on how your OS buffers stdout, but I am pretty sure it will work most places. printf() works on stdout. If you run this with the fflush() call commented out (as above), you will wait 3 seconds then see "Hello world". This is because the system holds data in the stdout buffer, as Common Tater says, up until some pre-determined point.* Each process (program) has it's own stdout stream, and when the program ends, it is flushed.

    But if you uncomment the fflush(stdout), you will see "Hello world" immediately, then wait 3 seconds for the program to end. Make sense?

    As a few people have observed, by the C standard you should not use fflush() on an input stream.
    Those IBM pages pop up for some googles and are often useful, but beware that they are referring to (potentially non-standard) IBM libraries.

    * for stdout, a newline is such a point on many systems. So if you add a \n to the end of the printf statement, this will flush the buffer right away.
    Last edited by MK27; 06-13-2011 at 09:00 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46
    So fflush should be used after output stream;
    if occures an error while writing output, calling fflush ensure that the data is printed to the output stream.

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by blob84 View Post
    So fflush should be used after output stream;
    You don't have to, but if you notice that the system is buffering stuff in a way that screws your logic up, then go ahead.

    if occures an error while writing output, calling fflush ensure that the data is printed to the output stream.
    Sort of. For example, if something between the printf() and the fflush() causes a segmentation fault, you will never see the output. This can be confusing if you are using printf() to debug such a fault (eg, to determine where it happens). You can always just call fflush() immediately after printf().

    However, a better option might be to use fprintf(stderr, ""), because stderr is a seperate stream which also appears (by default) on the console, but is guaranteed by the C standard to be unbuffered, meaning the system will immediately print it no matter what. A possible complication with this is that the user can redirect stdout and stderr differently, and if they (eg) redirect stdout to a file, the fprintf(stderr) stuff will not go there -- it will still appear on the screen. That is actually a handy feature, since it allows you to separate your proper output from error messages, but beware of the difference, and that it is probably not a good practice to use stderr for your normal output.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by blob84 View Post
    So fflush should be used after output stream;
    if occures an error while writing output, calling fflush ensure that the data is printed to the output stream.
    More or less... it forces the stuff in the memory buffers to be written out, which will reduce the risk of data loss if an error does occur before the buffers write it out on their own.
    Last edited by CommonTater; 06-13-2011 at 11:00 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fflush() help
    By frs in forum Linux Programming
    Replies: 1
    Last Post: 07-15-2010, 07:00 PM
  2. getchar or fflush
    By nik2 in forum C Programming
    Replies: 5
    Last Post: 04-27-2010, 06:51 PM
  3. fflush
    By raja9911 in forum C Programming
    Replies: 2
    Last Post: 02-09-2006, 02:02 AM
  4. To fflush, or Not to fflush...
    By bjgough in forum C Programming
    Replies: 32
    Last Post: 08-19-2005, 12:56 AM
  5. fflush
    By Shogun in forum C Programming
    Replies: 1
    Last Post: 05-16-2003, 09:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21