What is fflush in C?

The fflush function in C is used to immediately flush out the contents of an output stream.

This is particularly useful in displaying output, as the operating system may initially put the output data in a temporary buffer before writing it to an output stream or file like stdout.

To use the fflush function, the <stdio.h> library must be included.

#include <stdio.h>

Syntax

The syntax for the fflush function is shown below:

int fflush(FILE *stream);

Parameters

The fflush function only takes in one parameter, a pointer to a FILE object. For example, this FILE Object could be stdout.

Return value

If executed successfully, the fflush function returns 0. Otherwise, it returns End Of File, abbreviated as EOF.

Example

Buffering works in such a way that the contents of an output buffer are only written to the stdout stream or FILE object once the buffer is full, or there is a new line character at the end of it. This may result in unexpected behavior. For instance, in the code below, the user may not see the string passed in the printf function on their terminal as it is not large enough to fill the buffer completely, nor is there a new line character at the end of it.

Here, the programmer can use the fflush function to make sure that the current state of the buffer is immediately printed to the console and written to the stdout stream. This is as shown below:

#include <stdio.h>
int main()
{
printf("Welcome to Educative!");
fflush(stdout);
}

In the example below, we demonstrate how to execute the files named test.c and secondtest.c with the fflush method placed in different positions. This helps in understanding the behavior of the fflush method. Before running these files, it's recommended to see the code in the files using cat filename command to observe the placement of the fflush method in both files.

To run these files, please use the following command:

  • For test.c: type clang test.c -o test && ./test command.

  • For secondtest.c: type clang secondtest.c -o secondtest && ./secondtest command.

Terminal 1
Terminal
Loading...

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved