The answer to this is that fflush(stream) is only formally defined for output streams, so fflush(stdout) is OK, but fflush(stdin) is not.

The purpose of fflush(stream) is to make the operating system flush any buffers to the underlying file. For an example of a legitimate use, students often have problems like “my prompt doesn't appear!” if they do something like:

printf("Enter a number: ");

However, they find that this works just fine:

printf("Enter a number:\n");

Of course, they don't want a newline after their prompt, so they have a bit of a problem.

The reason for this is that the output to stdout is buffered by the OS and the default behavior is (often) only to actually write the output to the terminal when a newline is encountered. Adding an fflush(stdout) after the printf() solves the problem:

printf("Enter a number: ");
fflush(stdout);

Now, working by analogy, people often think that fflush(stdin) should discard any unused input, but if you think about it a little bit that doesn't make much sense. What does it mean to “flush” an input buffer? Where is it “flushed” to? If you flush an output buffer, the output is sent to the underlying file or the terminal, where it would eventually wind up anyway, but where would input “eventually end up anyway”? There's no way of knowing! What should the behavior be if the input stream data comes from a file or a pipe or a socket? It isn't at all clear for input streams what the behavior of fflush() should be, but it's very clear for output streams in all cases. Hence, fflush() is only defined for output streams.

The reason why the erroneous use of fflush(stdin) became commonplace is that, many years ago, a few operating systems did implement a scheme where it worked as many people expected, discarding unused input. Microsoft DOS is a good example. Surprisingly, modern versions of Linux also implement fflush() for input streams.

The right thing to do with “extra” unwanted terminal input is simply to read it and do nothing with it. This is almost as easy as calling fflush(stdin), works everywhere, and doesn't rely on formally undefined behavior.

The C standard says:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

POSIX says (also explicitly defers to C standard):

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() shall cause any unwritten data for that stream to be written to the file, ...

But the Linux manpage says:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application. The open status of the stream is unaffected.

Answer from Emmet on Stack Overflow
🌐
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.
🌐
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.
Discussions

c - what is the different of using fflush(stdout) and not using it - Stack Overflow
This means the output is buffered inside the computer internals until a full line is received (and output). Your programs do not send a full line to the computer internals. In the case of using fflush() you are telling the computer internals to send the current data in the buffer to the device; ... More on stackoverflow.com
🌐 stackoverflow.com
[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
Programming in C - the fflush function
You need to know what IO buffering is and how it works to understand what fflush() does and when to use it. If I can read between the lines a little bit and try to understand your professor's reasoning, flushing is only a defined operation on an output stream. When you write to a stream, if buffering is enabled, the written data is stored in a buffer and not actually physically written to the stream. When the buffer fills, the data is written. This is done to improve performance, because it allows for making fewer syscalls, since lots of small writes can be aggregated into a fewer number of large writes. But there are times when you explicitly need to cause the output buffer to be flushed, and that is what fflush() is for. It wouldn't be part of standard C if there wasn't a good reason for it to exist. As I mentioned, in standard C flushing is only defined for output streams, not input streams. But input streams often have buffering as well, but for different reasons (although syscall overhead is still relevant.) For example, if you are interacting with a stream that is connected to a terminal or console, it will usually be line buffered. This allows for things like line editing (for example, the ability for the user to use backspace to correct a mistake and retype it) without that functionality having to be explicitly implemented by the programmer. But that means that you don't see any of the user's input until they've pressed return. This often trips up learners, because if you don't read input as a complete line — for instance, if you read only a whitespace-delimited token but the input contained additional characters — then it potentially leaves input still in the buffer unread, which will cause the next read call to immediately return without waiting for input. Some garbage people write garbage tutorials that contain garbage advice like using fflush() on an input stream when faced with the above problem. The idea is to discard the rest of the input buffer. However, that's implementation-specific behavior, and is not portable. Again, fflush() is only defined in standard C for output streams; the behavior on an input stream is implementation-defined. Only on Windows does flushing an input stream cause it to drop the contents of the buffer. So this is a bad idea for multiple reasons, and you shouldn't do that. The proper way to deal with it is to read input a line at a time. There is no need for ugly hacks if you do things properly. I'm assuming that's what your professor was trying to teach you, but it sounds like they did it in a horrible way. More on reddit.com
🌐 r/learnprogramming
6
0
October 2, 2017
avoiding the fflush(stdin)
🌐 r/C_Programming
7
4
May 5, 2017
Top answer
1 of 2
47

The answer to this is that fflush(stream) is only formally defined for output streams, so fflush(stdout) is OK, but fflush(stdin) is not.

The purpose of fflush(stream) is to make the operating system flush any buffers to the underlying file. For an example of a legitimate use, students often have problems like “my prompt doesn't appear!” if they do something like:

printf("Enter a number: ");

However, they find that this works just fine:

printf("Enter a number:\n");

Of course, they don't want a newline after their prompt, so they have a bit of a problem.

The reason for this is that the output to stdout is buffered by the OS and the default behavior is (often) only to actually write the output to the terminal when a newline is encountered. Adding an fflush(stdout) after the printf() solves the problem:

printf("Enter a number: ");
fflush(stdout);

Now, working by analogy, people often think that fflush(stdin) should discard any unused input, but if you think about it a little bit that doesn't make much sense. What does it mean to “flush” an input buffer? Where is it “flushed” to? If you flush an output buffer, the output is sent to the underlying file or the terminal, where it would eventually wind up anyway, but where would input “eventually end up anyway”? There's no way of knowing! What should the behavior be if the input stream data comes from a file or a pipe or a socket? It isn't at all clear for input streams what the behavior of fflush() should be, but it's very clear for output streams in all cases. Hence, fflush() is only defined for output streams.

The reason why the erroneous use of fflush(stdin) became commonplace is that, many years ago, a few operating systems did implement a scheme where it worked as many people expected, discarding unused input. Microsoft DOS is a good example. Surprisingly, modern versions of Linux also implement fflush() for input streams.

The right thing to do with “extra” unwanted terminal input is simply to read it and do nothing with it. This is almost as easy as calling fflush(stdin), works everywhere, and doesn't rely on formally undefined behavior.

The C standard says:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

POSIX says (also explicitly defers to C standard):

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() shall cause any unwritten data for that stream to be written to the file, ...

But the Linux manpage says:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application. The open status of the stream is unaffected.

2 of 2
20

fflush(stdin) invokes undefined behaviour.

fflush() is defined only for output streams. You should not do it.


On Unix, Ctrl-Z sends a TSTP signal (SIGTSTP) which by default causes the process to suspend execution.

🌐
Scaler
scaler.com › home › topics › fflush() in c
fflush() in C - Scaler Topics
May 4, 2023 - Buffer is a temporary memory (mainly ... is provided by the unbuffered function. fflush() function in C is used to flush the buffer of any stream present in RAM, which means it prints the data of the buffer to the respective file ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › use-fflushstdin-c
Use of fflush(stdin) in C - GeeksforGeeks
September 15, 2023 - The code above takes only single input and gives the same result for the second input. Reason is because as the string is already stored in the buffer i.e. stream is not cleared yet as it was expecting string with spaces or new line. So, to handle this situation fflush(stdin) is used.
🌐
TechOnTheNet
techonthenet.com › c_language › standard_library_functions › stdio_h › fflush.php
C Language: fflush function (Flush File Buffer)
In the C Programming Language, the fflush function writes any unwritten data in stream's buffer. If stream is a null pointer, the fflush function will flush all streams with unwritten data in the buffer.
🌐
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
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › use-of-fflush-stdin-in-c
Use of fflush(stdin) in C
June 24, 2020 - The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and feof error indicator is set. Here is the syntax of fflush(stdin) in C language,
🌐
W3Resource
w3resource.com › c-programming › stdio › c_library_method_fflush.php
C fflush() function
C fflush() function: The fflush() function is used to empty the buffer that is associated with the specified output stream, if possible. The fflush() function undoes the effect of any ungetc() function if the stream is open for input.
🌐
Fresh2Refresh
fresh2refresh.com › home › c programming tutorial › c – file handling › fflush() function in c
fflush() function in C | C File Handling | Fresh2Refresh
September 22, 2020 - fflush() function in C:fflush() function is a file handling function in C programming language which is used to flush/clean the file or buffer. Please
🌐
cppreference.com
en.cppreference.com › w › c › io › fflush.html
fflush - cppreference.com
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.
🌐
IncludeHelp
includehelp.com › c-programs › fflush-function-in-c-language-with-example.aspx
fflush() function in C language with Example
There are three types of streams stdin (standard input), stderr (standard error), stdout (standard output). fflush() function is used to flush the buffer after each iteration in the program. When we open a file for the write operation, a call to fflush() function helps to write on the file ...
Top answer
1 of 2
10

In a normal C program running on a modern OS, file access is buffered twice (or more when you count buffers like the buffer in your drive). One buffer is implemented in the FILE structure and the other is implemented in the kernel.

Often, the FILE structure buffers the content in a buffer inside of your program. When you write something to a buffered file, the content is keep in the buffer, inside of the running program. It is written to the OS when the buffer is full and, when the buffering mode is line buffered, at the end of a line. This data is written to the OS by a syscall, for example write(). The buffer is there because a syscall requires a context switch from the user program to the kernel, this is relatively expensive (slow), the buffer is here to reduce the number of syscalls. You could also use the syscalls from your program directly without the stdio functions, however, this functions are less portable and more complex to handle. A fflush(stdout) checks if there are any data in the buffer that should be written and if so, the underlying syscall is used to write the data to the OS.

When the syscall returns, the data is in your kernel. But modern operating systems buffer this data as well. This is used to reduce the number of disk writes, reduce latency and other things. This buffer is completely independent of the FILE buffer inside your program.

Note that this does not apply to all systems. For example microcontroller environments may provide some stdio.h functions that write directly to a UART, without any buffer, neither inside FILE nor any (probably non-existent) OS.

To see what fflush() does to a running program, compare this programs:

int main(void)
{
  fputs("s",stdout);
  fputs("e",stderr);
}

and

int main(void)
{
  fputs("s",stdout);
  fflush(stdout);
  fputs("e",stderr);
}

On Linux, stderr is not buffered by default, so fputs("e",stderr); will print the data immediately. On the other hand, fputs("s",stdout); is line buffered by default on Linux so the data is not printed immediately. This causes the first program to output es and not se, but the second one outputs se.

You can change the buffer modes with setvbuf()

2 of 2
5

When stdout points to a tty, it is, by default, line-buffered. This means the output is buffered inside the computer internals until a full line is received (and output).

Your programs do not send a full line to the computer internals.

In the case of using fflush() you are telling the computer internals to send the current data in the buffer to the device; without fflush() you are relying on the computer internals to do that for you at program termination.

By computer internals I mean the combination of the C library, Operating System, hardware interface, (automatic) buffers between the various interfaces, ...

🌐
PrepBytes
prepbytes.com › home › c programming › fflush() in c
fflush() in C
August 18, 2023 - The fflush function in C is used to flush the buffer of any stream present in RAM, which means it prints the data of the buffer to the corresponding file in the main memory.
🌐
Quora
quora.com › What-is-fflush-stdin-in-a-C-language
What is fflush (stdin); in a C language? - Quora
I have read most of the answers for this question, and they all say its to clear the input stream. To them I say, start reading the C standard before giving out such answers. Though [code ]fflush()[/code] function is used to clear a stream, using ...
🌐
Linux Hint
linuxhint.com › fflush-function-c-programming
How to use fflush function in C programming – Linux Hint
The fflush() function is the abbreviation of the “flush file buffer”, as it is clear from its name that its function is to clear some content. In C programming, it is used to clear the buffer so that the output stream(stdout) can display the output.
🌐
Cplusplus
cplusplus.com › reference › cstdio › fflush
fflush
In files open for update (i.e., open for both reading and writing), the stream shall be flushed after an output operation before performing an input operation. This can be done either by repositioning (fseek, fsetpos, rewind) or by calling explicitly fflush, like in this example:
🌐
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".

🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › fflush
fflush | Microsoft Learn
December 2, 2022 - The fflush function flushes the stream stream. If the stream was opened in write mode, or it was opened in update mode and the last operation was a write, fflush writes the contents of the stream buffer to the underlying file or device, and ...