Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is fflush in C?

Rukhshan Haroon

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}

RELATED TAGS

c

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring