Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use fflush() in C++

Sadia Zubair

The fflush function is a C library function that flushes the output buffer of the stream.

In the case of standard output, the output buffer is moved to the console. In the case of the file output stream, the output buffer is transferred to disk.

In order to use the fflush function, the stdio header file needs to be included in the program, as shown below:

#include <stdio.h>
Figure 1 : Function declaration

Parameters

The function receives one parameter: a pointer to a FILE object that specifies a buffered stream.

Return value

Upon successful execution of the function, zero is returned. End-of-File (EOF) is returned in case of any error, and the error indicator of the file stream is set.

Example

The code below shows how the fflush function works in C++.

In line 9, the file is open for reading and writing. To do this, the stream is flushed after an output operation and before performing an input operation. This is done by explicitly calling the fflush function in line 11, as shown below:

main.cpp
demo.txt
#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
   char mybuffer[800];
   FILE * file;
   file = fopen ("demo.txt","r+");
   fputs ("test",file);
   fflush (file);    // flushing required
   fgets (mybuffer,800,file);
   cout << mybuffer << endl;
   fclose (file);
   return 0;
  
}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring