×

fflush in C

In this article, we will understand what is fflush(), the need for fflush and fflush(stdin), and fflush(stdout).

The fflush() function is used to clear the output buffer and move the buffered data to the console or disk. It is basically used for output stream only.

The fflush(flush to file) function flushes the content of any output stream to the corresponding file.

Syntax of fflush

fflush(FILE *ostream)

Here, ostream will point to the update or output stream in which the recent operation is not an input operation.  The function that causes any non-written data (for that stream) to be delivered to the host environment should be written in the file; otherwise, it acts as undefined.

Need of fflush()

The problems faced in output buffering is shown below -

Code

#include <stdio.h> 
int main() {
    fprintf(stdout, "This is to stdout. "); // statement 1 prints to stdout
    fprintf(stderr, "This is to stderr. "); // statement 2
    fprintf(stdout, "This is also to stdout.");// statement 3
}

The output expected was in order, but it comes out a bit different as -

This is to stderr. This is to stdout. This is also to stdout.

It happens because, by default, stdout is a new line-buffered, and stderr is unbuffered. In clear terms, for stdout until there is a new line, the content will be stored in the same temporary buffer. This is the reason that there is no newline.

For stderr, it is unbuffered, so the content is immediately written there.

Hence until we reach the end of the file(output end), the content of the stdout will be written in new lines.

Now let us add fflush() after every stdout.

Code

#include <stdio.h>
int main() {
    fprintf(stdout, "This is to stdout. "); // statement 1
    // Flush the contents of the output stream immediately
    fflush(stdout);
    fprintf(stderr, "This is to stderr. "); // statement 2 
    // No need to flush stderr since it is un-buffered
    fprintf(stdout, "This is also to stdout. "); // statement 3 
    fflush(stdout); // adding stdout after statement 3 
}

This time the output generated is -

                   This is to stdout. This is to stderr. This is also to stdout.

Here we have added fflush after statement 1 and after statement 3, and we get the output as desired. There was no need to add fflush for stderr as it is unbuffered.

fflush(stdin)

We cannot use fflush for stdin because buffering to the output screen makes logical sense as we know it will eventually be printed on the screen. And for inputs, there is no way to know when the inputs will end eventually. Thus, fflush(stdin) gives undefined behavior.

For taking inputs that contain spaces between them, we can use fflush(stdin).

Code

#include <stdio.h>
#include<stdlib.h>
int main()
{
	char str[20]; // create char array 
	int i;
	for (i=0; i<2; i++) // take two inputs 
	{
		scanf("%[^\n]s", str); // take input 
		printf("%s\n", str); // print input 
		fflush(stdin);  // clearing the buffer to take second input 
	}
	return 0;
}

Input

Java

Javatpoint

Output

Java

Javatpoint

Note: We can use fflush() after the scanf() function as it also clears the buffer, but due to the undefined behavior, it is not recommended to use fflush(stdin).


Related Topics

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

C Program for Mean and Median of an Unsorted Array

In this tutorial, we will look at how to determine the mean and median of a given unsorted array. To determine the Mean: To get the average, mean is determined. The formula...

2 minutes read.

Exit control loop in C

To examine the termination condition for an exit, we usually use an exit control loop in C. If the evaluation for termination condition results in true, then the control would...

3 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Entry Control Loop in C

Initially, an entry control loop verifies the termination condition at the entry point. After that, its control passes to the main body of the while or for loop if the...

3 minutes read.

pow() function in C

pow() function is one of the in-built functions present in math.h header file Power function is used to calculate the powers of the given number. The syntax of the power...

3 minutes read.

Unformatted input() and output() function in C

Unformatted Input and Output functions take the character, character array, and strings as input. We can read-only character data types with these functions. These functions are already defined in the...

5 minutes read.

How to return a Pointer from a Function in C?

In the C programming language, pointers are variables that hold the address memory location of another variable. We could also input pointers to a function and return pointers from a...

3 minutes read.

function pointer as argument in C

Pointers are considered difficult to understand for beginners but pointers can be made to work if you fiddle with them long enough. So, let’s understand this step by step. What are...

3 minutes read.

Character Class Tests in C

Introduction The <ctype.h> is a header file in C which is used to declare functions for testing characters. This header file of the C standard library is used to declare multiple...

4 minutes read.

Hook() function in C

Use of hook () function in C Introduction:  The hook () is a function used in the C programming language. The basic concept of the hook() function is that it can remove the function...

3 minutes read.

Decimal to Hexadecimal in C

Decimal to Hexadecimal in C Let us first understand the definitions of decimal and hexadecimal. In algebra, a decimal number is defined as a number whose whole number part and a...

3 minutes read.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

Find a subarray with a given sum.

Find a subarray with a given sum. The simple solution is to recognize all subarrays one by one and to check each subarray's sum. The quick solution follows the following program. Algorithm: From...

4 minutes read.

C –Structure

C structure is a collection of different types of data that is grouped together. It is used to represent records.Structkeyword is used to create a structure. Each element of a...

1 minute read.

Int in C

The keyword int in C programming stands for integer and it is a data type which is used for variable declarations or declaration of functions of different types. Similar to...

4 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Comments in C

Comments are used to comment on the line of code in the program. Comments are a way of inserting remarks and reminders into code without affecting its behavior. The compiler...

1 minute read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.