C++ fflush()

Buffered data is the temporary or application specific data stored in the physical memory of the computer until a certain time.

The fflush() function is defined in <cstdio> header file.

fflush() prototype

int fflush(FILE* stream);

If stream is an output stream or update stream whose last operation was output, calling the fflush() function will write any buffered unwritten data to the associated output device.

If stream is a null pointer, all open output streams are flushed.

The behaviour is undefined for input streams and update streams whose last operation was input.


fflush() Parameters

  • stream: The stream to be flushed.

fflush() Return value

The fflush() function returns:

  • Zero on success.
  • EOF on failure and sets the error indicator of the file stream.

Example: How fflush() function works?

#include <cstdio>
#include <cstring>

int main()
{
	int x;
	char buffer[1024];

	setvbuf(stdout, buffer, _IOFBF, 1024);
	printf("Enter an integer - ");

	fflush(stdout);

	scanf("%d",&x);
	printf("You entered %d", x);

	return(0);
}

When you run the program, the output will be:

Enter an integer - 2
You entered 2

In the above program, try removing the line fflush(stdout) and run the program to see the effect of fflush. The string "Enter an integer - " won't be written to the screen unless it is flushed.

Did you find this article helpful?