In this write-up, we will explain the fflush() function in C programming with the help of examples.
What is fflush() function in C programming
Before understanding the fflush(), we will understand what is a buffer? Let’s consider an example; we are watching a season on Netflix, the Netflix continuously buffers the contents of video for the next few minutes, so you do not need to wait for the video to load, this downloading is known as buffering. In C programming the buffer works the same way. The stored values in the buffer can become the reason for unexpected results.
To clear the buffer, we use the fflush() function. Let’s consider an example:
Type the code in the text file, testfile.c, and then compile this file using a compiler, as we are using Linux, so we will compile the file using the gcc compiler:
The file has been compiled without any errors and warnings, so we will execute the above code
The output of the above file is not expected, the ”This is Linuxhint.” should be printed before the “This is about fflush()” but it didn’t happen. Because the “stdout” is by default a buffer so it will store the values in the temporary buffer whereas the stderr is not buffered so it displayed the output immediately, and the stdout will display the output of its file from buffer memory either when the program ends or the new line terminator(“\n”) is used.
According to this, the output is displayed in the unexpected order, to print it in a sorted way, we will use the ffllush() function:
Compile the file using the gcc compiler:
Execute the file using the command:
Now the results are sorted because the fflush() cleared the buffered memory and displayed the output.
The fflush() function is used to clear the buffer memory and display the results of outputstream (stdout). In this write-up, we have explained the fflush() function in C programming with the help of examples. The fflush() function is recommended to use with the stdout because stdout is by default a buffer and saves its data into the temporary buffer memory.