13.23. fflush()

Process all buffered I/O for a stream right now

Prototypes

#include <stdio.h>
int fflush(FILE *stream);

Description

When you do standard I/O, as mentioned in the section on the setvbuf() function, it is usually stored in a buffer until a line has been entered or the buffer is full or the file is closed. Sometimes, though, you really want the output to happen right this second, and not wait around in the buffer. You can force this to happen by calling fflush().

The advantage to buffering is that the OS doesn't need to hit the disk every time you call fprintf(). The disadvantage is that if you look at the file on the disk after the fprintf() call, it might not have actually been written to yet. ("I called fputs(), but the file is still zero bytes long! Why?!") In virtually all circumstances, the advantages of buffering outweigh the disadvantages; for those other circumstances, however, use fflush().

Note that fflush() is only designed to work on output streams according to the spec. What will happen if you try it on an input stream? Use your spooky voice: who knooooows!

Return Value

On success, fflush() returns zero. If there's an error, it returns EOF and sets the error condition for the stream (see ferror().)

Example

In this example, we're going to use the carriage return, which is '\r'. This is like newline ('\n'), except that it doesn't move to the next line. It just returns to the front of the current line.

What we're going to do is a little text-based status bar like so many command line programs implement. It'll do a countdown from 10 to 0 printing over itself on the same line.

What is the catch and what does this have to do with fflush()? The catch is that the terminal is most likely "line buffered" (see the section on setvbuf() for more info), meaning that it won't actually display anything until it prints a newline. But we're not printing newlines; we're just printing carriage returns, so we need a way to force the output to occur even though we're on the same line. Yes, it's fflush()!

#include <stdio.h>
#include <unistd.h> // for prototype for sleep()

int main(void)
{
    int count;

    for(count = 10; count >= 0; count--) {
        printf("\rSeconds until launch: ");  // lead with a CR
        if (count > 0)
            printf("%2d", count);
        else
            printf("blastoff!\n");

        // force output now!!
        fflush(stdout);

        // the sleep() function is non-standard, but virtually every
        // system implements it--it simply delays for the specificed
        // number of seconds:
        sleep(1);
    }

    return 0;
}

See Also

setbuf(), setvbuf()