C Library - fflush() function



The C library fflush() function flushes the output buffer of a stream.This function forces a write of all buffered data for the given output or update stream to the file. When applied to an input stream, its behavior is undefined. Flushing the stream ensures that any data buffered in memory is written out to the file or device associated with the stream.

Syntax

Following is the C library syntax of the fflush() function −

int fflush(FILE *stream);

Parameter

  • stream: This is a pointer to a FILE object that specifies the stream to be flushed. If stream is NULL, fflush flushes all open output streams.

Return Value

The fflush function returns 0 i.e Success when the buffer was successfully flushed.It returns EOF i.e failure if an error occurred, and the error indicator for the stream is set.

Example 1: Flushing Output Stream

This example shows how fflush can be used to ensure that buffered output is written to a file immediately.

Below is the illustration of C library fflush() function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   fprintf(file, "Hello, World!\n");

   // Ensure "Hello, World!" is written to the file immediately
   fflush(file); 

   fclose(file);
   return 0;
}

Output

The above code writes "Hello, World!" to a file and uses fflush to ensure the data is written to the disk immediately, instead of waiting for the file to close.−

Hello, World!

Example 2: Flushing All Open Output Streams

Now in this example we write different data to two files and uses fflush(NULL) to flush all open output streams, ensuring all data is written to disk before closing the files.

#include <stdio.h>

int main() {
   FILE *file1 = fopen("example3_1.txt", "w");
   FILE *file2 = fopen("example3_2.txt", "w");
   if (file1 == NULL || file2 == NULL) {
       perror("Failed to open file");
       return 1;
   }
   
   fprintf(file1, "Data for file 1.\n");
   fprintf(file2, "Data for file 2.\n");
   
   // Flush all open output streams
   fflush(NULL); 
   
   fclose(file1);
   fclose(file2);
   return 0;
}

Output

After execution of above code,it writes different data to two files and uses fflush(NULL) to flush all open output streams, ensuring all data is written to disk before closing the files.

Data for file 1.
Data for file 2.
Advertisements