C library function -fflush()

C Standard Library - <stdio.h>

Description

C Library Functionsint fflush(FILE *stream)Used to flush the output buffer.

fflush() is a function in the C standard library that immediately writes the data in the buffer to the file or device associated with the stream.

For input streams, its behavior is undefined, and calling this function on input streams should be avoided.

Declaration

Below is the declaration of the fflush() function.

int fflush(FILE *stream)

Parameter

  • stream-- A pointer to type FILE, indicating the target stream whose buffer needs to be flushed. FILE is a structure representing an open file stream.

    • ifstreamisNULL, then it will flush the buffers of all output streams.
    • ifstreamIf it is a file pointer, then flush the output buffer of that file stream.

Return Value

  • If the buffer is successfully flushed,fflush()Returns 0.

  • If an error occurs, returnsEOF, and sets the error indicator (ferror)。

Example

The following example demonstrates the usage of the fflush() function.

Example

#include <stdio.h> int main() { FILE *fp; char *filename = "example.txt"; char *data = "Hello, World!"; // Open file for writing fp = fopen(filename, "w"); if (fp == NULL) { printf("Unable to open file %s\n", filename); return 1; } // Write data to file fprintf(fp, "%s", data); // Flush the buffer to ensure the data is written to the file if (fflush(fp) == 0) { printf("Data successfully written to the file.\n"); } else { printf("An error occurred while flushing the buffer.\n"); } // Close file fclose(fp); return 0; }

Code explanation:

  • Open a File: Usefopen()Open a file namedexample.txtThe file is opened for writing.

  • Write data: Usefprintf()The string"Hello, World!"Write to the file.

  • Flush the buffer: Callfflush(fp)Ensure that data is written to the file immediately, rather than remaining in the buffer.

  • Check the return value: iffflush()Returns 0, indicating that the buffer was flushed successfully; otherwise, it indicates that an error occurred.

  • Close a File: Usefclose()Close the file.

Data successfully written to the file.

The program opens the file example.txt and writes the string "Hello, World!".

fflush(fp) successfully flushes the buffer and returns 0, so it prints "Data successfully written to the file."

The content of the file example.txt will be:

Hello, World!

C Standard Library - <stdio.h>

other extensions