cs24-20fa fflush

Introduction to Computing Systems (Fall 2020)

Name

fflush - flush a stream’s buffer

Synopsis

#include <stdio.h>

int fflush(FILE *stream);

Description

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream’s underlying write function.

If stream is NULL, fflush() flushes all open output streams.

Example

#include <stdio.h>

int main() {
    // This line will be buffered because it doesn't end in a newline
    printf("This text is not followed by a newline");

    // Wait several seconds (compile with -O0 to prevent this being optimized out)
    for (size_t i = 0; i < 1000000000; i++) {}

    // Flush stdout's buffer. This will print the line to the terminal.
    fflush(stdout);

    // Wait again
    for (size_t i = 0; i < 1000000000; i++) {}
}

Return Value

Upon successful completion 0 is returned. Otherwise, EOF is returned and errno is set to indicate the error.

Errors

EBADF
stream is not an open stream, or is not open for writing.

fflush() may also fail and set errno for any of the errors specified for write().

See Also

fopen(), fclose(), fread(), fwrite()