fflush(stdin) does not work compiled with gcc in cygwin but does compiled with visual studio 2010

柔情痞子 提交于 2019-12-08 18:56:28

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, 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.

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.

In the standard, fflush() is not defined for input streams. In Microsoft's documentation it is explicitly defined.

The upshot is that while you can use it with Microsoft's C library with clearly defined behaviour, such behaviour is not portable.

If you want to use GCC and have this work, then you could use MinGW/GCC since that uses Microsoft's C runtime rather than glibc.

You should not fflush an input stream. The differences you observe came from the fact that the behaviour of this operations is undefined.

From what I understand, you are writing this program for Linux and believe it or not, fflush(stdin) only works under Windows. (That's at least what I got from my C book called C for dummies). The alternative for fflush(stdin) on Linux is fpurge(stdin). Try it out and see if it works for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!