Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fflush — C23 stream function

`fflush(stream)` from `<stdio.h>` delivers unwritten buffered data to the host environment for an output stream or a qualifying update stream. `fflush(NULL)` attempts this for every such open stream; the result is zero on success or `EOF` with the error indicator set on failure.

Version: C23

Syntax

int fflush(FILE *stream);

fflush(stream) from <stdio.h> delivers unwritten buffered data to the host environment for an output stream or a qualifying update stream. fflush(NULL) attempts this for every such open stream; the result is zero on success or EOF with the error indicator set on failure.

The example writes hello to a tmpfile(), calls fflush, rewinds the stream, and reads the data through fgets. Output 1 hello demonstrates a successful flush and a valid transition from writing to reading on an update stream.

Standard C does not define fflush(stdin) as a way to discard input: if the specified stream does not meet the output/update condition, behavior is undefined. Success means delivery to the host environment, not necessarily durable storage on physical media. Check for EOF; after failure, the error indicator remains set until a clearing operation such as clearerr or rewind.

Examples

#include <stdio.h>

int main(void) {
    FILE *stream = tmpfile();
    if (stream == NULL) return 1;
    if (fputs("hello", stream) == EOF) { fclose(stream); return 1; }
    int flushed = fflush(stream) == 0;
    rewind(stream);
    char buffer[6];
    if (fgets(buffer, sizeof buffer, stream) == NULL) { fclose(stream); return 1; }
    printf("%d %s\n", flushed, buffer);
    return fclose(stream) == 0 ? 0 : 1;
}

Result

1 hello

The example writes `hello` to a `tmpfile()`, calls `fflush`, rewinds the stream, and reads the data through `fgets`. Output `1 hello` demonstrates a successful flush and a valid transition from writing to reading on an update stream.

Sources