Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

Answer from Mike on Stack Overflow
Top answer
1 of 1
133

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

🌐
GeeksforGeeks
geeksforgeeks.org › c language › use-fflushstdin-c
Use of fflush(stdin) in C - GeeksforGeeks
September 15, 2023 - fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console (in case of stdout) or disk (in case of file output stream).
Discussions

[C++] What does flushing the buffer means ?
Imagine you're job is to change the marque just under the sign of a fast food restaurant. The message you want to display is "Open 24 hours". Here's one way to do it. Get a ladder Get a box of letters Find the capital O Climb the ladder Place the O Climb down the ladder Get the next letter Repeat until done No intelligent human would take these steps. It's too much work. But a computer is a slave to the program and will follow instructions with no complaints. So how would an intelligent human solve this problem? Here's how: Get a ladder Get a box of letters Get a bag Find the capital O Put it in the bag Find the next letter and repeat until all the letters are in the bag Climb the ladder Find the capital O Place the O Repeat placing each letter until finished Climb down the letter Notice how much less effort you had to exert by first putting all of the letters into the bag. That's because the work necessary to move the letters from the ground to the sign was only done once. Displaying a message in a computer is similar. While you may write a simple line of code to display a message, 1000s or 100,000s of lines of code are executed just to display your message. This is a lot of work. So for efficiency, your program's output is placed in a buffer. It's like our bag example, except it's more efficient since it's ordered. The first character that you want to display is the first thing in the buffer and so on. In the example with the bag, you had to find the letters all over again. Flushing a buffer is like emptying the bag. If you climb the ladder and don't empty the bag, your sign will say nothing. If your program exits WITHOUT flushing the buffer, then the data is never displayed. BTW, buffers are used everywhere. Network communications is one notable place. Imagine how much overhead it would be to write your friend a letter if you wrote one word on a piece of paper and then mailed that letter. Then wrote the next word on the next sheet and mailed that letter. We don't do that because it's inefficient. Instead we write all the words onto one or more sheets of paper and then mail them once. In network communications, we buffer the data we want to send until the buffer is full at which point it's automatically flushed or we have no more to send and we manually flush the buffer. Hope this helps. More on reddit.com
🌐 r/learnprogramming
10
6
December 20, 2014
[C] Can someone please explain fflush(stdin) to me?
understand that this command flushes out the input stream No. Calling fflush() on stdin is undefined in C - it could do anything. "flushing" means removing everything from a buffer. In the case of the stdout output stream (for which calling fflush() is defined), then whatever is in the streams internal buffers (private memory) will be sent to the actual output device - if this is the screen, then whatever was in the buffer will be displayed. For alternative ways of clearing the input stream buffer, see http://c-faq.com/stdio/stdinflush2.html . More on reddit.com
🌐 r/learnprogramming
10
9
July 1, 2015
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_fflush.htm
C Library - fflush() function
The C library fflush() function flushes the output buffer of a stream.This function forces a write of all buffered data for the given output or update stream to the file. When applied to an input stream, its behavior is undefined.
🌐
Reddit
reddit.com › r/learnprogramming › [c++] what does flushing the buffer means ?
r/learnprogramming on Reddit: [C++] What does flushing the buffer means ?
December 20, 2014 -

Hi, I am learning C++ . What does flushing the buffer means ? with respect to cin and cout?

Can anyone explain like i'm five Please?

Top answer
1 of 2
4
Imagine you're job is to change the marque just under the sign of a fast food restaurant. The message you want to display is "Open 24 hours". Here's one way to do it. Get a ladder Get a box of letters Find the capital O Climb the ladder Place the O Climb down the ladder Get the next letter Repeat until done No intelligent human would take these steps. It's too much work. But a computer is a slave to the program and will follow instructions with no complaints. So how would an intelligent human solve this problem? Here's how: Get a ladder Get a box of letters Get a bag Find the capital O Put it in the bag Find the next letter and repeat until all the letters are in the bag Climb the ladder Find the capital O Place the O Repeat placing each letter until finished Climb down the letter Notice how much less effort you had to exert by first putting all of the letters into the bag. That's because the work necessary to move the letters from the ground to the sign was only done once. Displaying a message in a computer is similar. While you may write a simple line of code to display a message, 1000s or 100,000s of lines of code are executed just to display your message. This is a lot of work. So for efficiency, your program's output is placed in a buffer. It's like our bag example, except it's more efficient since it's ordered. The first character that you want to display is the first thing in the buffer and so on. In the example with the bag, you had to find the letters all over again. Flushing a buffer is like emptying the bag. If you climb the ladder and don't empty the bag, your sign will say nothing. If your program exits WITHOUT flushing the buffer, then the data is never displayed. BTW, buffers are used everywhere. Network communications is one notable place. Imagine how much overhead it would be to write your friend a letter if you wrote one word on a piece of paper and then mailed that letter. Then wrote the next word on the next sheet and mailed that letter. We don't do that because it's inefficient. Instead we write all the words onto one or more sheets of paper and then mail them once. In network communications, we buffer the data we want to send until the buffer is full at which point it's automatically flushed or we have no more to send and we manually flush the buffer. Hope this helps.
2 of 2
2
You print some text, it isn't showing in the terminal. Why isn't it showing? The buffer hasn't been flushed? Why is stdio buffered? Because printing characters is an expensive operation so you want to batch it. How do I flush it ? std::cout<
🌐
Educative
educative.io › answers › what-is-fflush-in-c
What is fflush in C?
The fflush function in C is used to immediately flush out the contents of an output stream.
🌐
Scaler
scaler.com › home › topics › fflush() in c
fflush() in C - Scaler Topics
May 4, 2023 - Data in buffer memory getflushedwhen any new-line character (‘\n’) hits, buffer memory becomes full, or any unbuffered function is called. Now, buffered output functions are those functions whose output is stored in the buffer memory, and the unbuffered output functions are those functions whose output didn’t score in the buffer and it flushes the buffer as well.
Find elsewhere
🌐
The Open Group
pubs.opengroup.org › onlinepubs › 000095399 › functions › fflush.html
fflush
The following example uses printf() calls to print a series of prompts for information the user must enter from standard input. The fflush() calls force the output to standard output. The fflush() function is used because standard output is usually buffered and the prompt may not immediately ...
🌐
Linux Man Pages
man7.org › linux › man-pages › man3 › fflush.3.html
fflush(3) - Linux manual page
To ensure that the data is physically stored on disk the kernel buffers must be flushed too, for example, with sync(2) or fsync(2). fsync(2), sync(2), write(2), fclose(3), fileno(3), fopen(3), fpurge(3), setbuf(3), unlocked_stdio(3) This page is part of the man-pages (Linux kernel and C library user-space interface documentation) project.
🌐
Quora
quora.com › What-does-fflush-stdout-do-in-C-and-how-do-you-use-it
What does fflush (stdout) do in C, and how do you use it? - Quora
Answer (1 of 3): Personally, I only find any use in calling fflush(stdout) after making a call to something like “setvbuf(stdout, NULL, _IOFBF, size)”. To understand fflush, you must first understand that when you do write operations (that print to the console, in the case of stdout), what actua...
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › fflush
fflush | Microsoft Learn
December 2, 2022 - When setting up a critical error ... _close, and _write instead of the stream I/O functions. The fflush function flushes the stream stream....
🌐
George Washington University
www2.seas.gwu.edu › ~simhaweb › C › modules › appendix › misc › misc.html
Software Development
int main () { int A[10]; int *B; int i; printf ("Before first for-loop\n"); fflush (stdout); for (i=0; i<10; i++) { A[i] = 1; } printf ("After first for-loop\n"); fflush (stdout); for (i=0; i<10; i++) { B[i] = A[i]; } printf ("After second for-loop\n"); fflush (stdout); } Upon compilation and execution, we see the following output: % gcc -o flush flush.c % flush Before first for-loop After first for-loop Segmentation fault (core dumped) Now we know the seg-fault occurs in the second loop.
🌐
Cppreference
en.cppreference.com › w › cpp › io › manip › flush.html
std::flush - cppreference.com
September 16, 2023 - Flushes the output sequence os as if by calling os.flush().
🌐
GNU
gnu.org › software › libc › manual › html_node › Flushing-Buffers.html
Flushing Buffers (The GNU C Library)
If you want to flush the buffered output at another time, call fflush, which is declared in the header file stdio.h.
🌐
Reddit
reddit.com › r/learnprogramming › [c] can someone please explain fflush(stdin) to me?
r/learnprogramming on Reddit: [C] Can someone please explain fflush(stdin) to me?
July 1, 2015 -

I understand that this command flushes out the input stream but what does it mean by "flushing the stream".

🌐
cppreference.com
en.cppreference.com › w › c › io › fflush.html
fflush - cppreference.com
If stream is a null pointer, all open output streams are flushed, including the ones manipulated within library packages or otherwise not directly accessible to the program. Returns zero on success. Otherwise EOF is returned and the error indicator of the file stream is set. POSIX extends the specification of fflush by defining its effects on an input stream, as long as that stream represents a file or another seekable device: in that case the POSIX file pointer is repositioned to match the C stream pointer (which effectively undoes any read buffering) and the effects of any ungetc or ungetwc that weren't yet read back from the stream are discarded.
🌐
Quora
quora.com › Can-you-explain-the-purpose-of-the-fflush-function-in-C-programming-language-How-did-it-get-its-name-Are-there-any-other-functions-with-similar-names-in-C
Can you explain the purpose of the 'fflush()' function in C programming language? How did it get its name? Are there any other functions with similar names in C? - Quora
The purpose of fflush(stream) is to make the operating system flush any buffers to the underlying file. ... char buff[1024]; memset( buff, '\0', sizeof( buff )); fprintf(stdout, "Going to set full buffering on\n"); setvbuf(stdout, buff, _IOFBF, ...
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › buffer-flush-means-c
What does buffer flush means in C++ ? - GeeksforGeeks
May 20, 2024 - Thus when we save our work, the changes that we've made to our document since the last time we saved it are flushed from the buffer to permanent storage on the hard disk. In C++, we can explicitly be flushed to force the buffer to be written. Generally, the std::endl function works the same by inserting a new-line character and flushes the stream.
Top answer
1 of 1
2

I think that flushing the buffer doesn't imply it will be printed to the screen or whatever stdout is redirected to.

Flushing stdout by reading from stdin:

You can achieve the behavior the following buf.c:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
  printf("Hello");
  sleep(2);
  fprintf(stderr, "No output from stdout after 2 seconds\n");

  char buf[10];
  while (fread(buf, sizeof(char), 10, stdin) == 10) {
  }

  sleep(5);
}

Run it:

$ ./buf
No output from stdout after 2 seconds
Hello

"Hello" string is printed to stdout and does not end with a newline) (\n) so it's not flushed after 2 seconds but it's flushed when fread() is run. If it was removed it would be flushed only after last sleep.

Whenever an input operation on any stream actually reads data from its file.

Flushing to file by reading from file:

To reproduce Whenever an input operation on any stream actually reads data from its file. which I think was your main goal:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
  FILE *fp = fopen("FILE", "a+");
  fprintf(fp, "add more characters to FILE\n");
  fprintf(stderr, "wrote more characters to FILE\n");
  sleep(5);

  fprintf(stderr, "reading will now start\n");
  fseek(fp, 0, SEEK_SET);
  char buf[10];
  while (fread(buf, sizeof(char), 10, fp) == 10) {

  }

  fprintf(stderr, "Sleep for 5 seconds before sleep()\n");
  sleep(5);
  fprintf(stderr, "Exit\n");
}

Run it like that, I will a small FILE that only contain a current date and will run a binary in the background so that I would be able to see all messages it prints and be able to examine contents of FILE at the same time:

$ date > FILE
$ ./buf &
[1] 14522
wrote more characters to FILE
$ cat FILE
Sat Nov  9 13:02:28 CET 2024
$ reading will now start
Sleep for 5 seconds before sleep()

$ cat FILE
Sat Nov  9 13:02:28 CET 2024
add more characters to FILE
Exit

As you see add more characters to FILE line has been added to FILE only after fread() was run.

🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re73.html
fflush - C in a Nutshell [Book]
December 16, 2005 - In the following example, the program fflush.c writes two lines of text to a file. If the macro FLUSH is defined, the program flushes the file output buffer to disk after each line. If not, only the first output line is explicitly flushed.
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618