C11 at 7.21.5.2.2 says (emphasis mine):
If
stream
points to an output stream or an update stream in which the most recent operation was not input, thefflush
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.
This means that you shouldn't call fflush
on an input stream (unless you are writing code for a very specific operating system and library where the behavior is defined)
There is a good reason for it! You would normally think that fflush(stdin)
would flush the line you have just entered, right? Well there's more to it. Imagine running your program like this:
$ ./program < input_file
In this case, all the file is theoretically already in the buffer of stdin
. Therefore, flushing that buffer equals ending your input which is quite a useless operation. For such reasons, fflush
cannot have a very sensible behavior on input streams and that's why it's undefined on them.
If you want to ignore the current line, there are better ways to do it. One example is the following:
void flush_line(FILE *fin)
{
int c;
do
{
c = fgetc(fin);
} while (c != '\n' && c != EOF);
}
This reads the input character by character and stops until either end-of-file, read error or end-of-line occurs.