linux下fflush(stdin)的使用问题

参考自linux下如何清空(刷新)stdin缓冲区


首先,fflush在C/C++/POSIX标准中只定义了处理输出流的行为,对于像stdin这种输入流,这是未定义行为undefined behavior,随便C/C++库怎么去实现都不算错。即使某个C/C++库对fflush(stdin)的处理是删除掉你硬盘上所有文件都没有错。所以你根本不要指望任何未定义行为能在不同平台下有相同的表现。

再来看看linux对fflush(stdin)的说法
代码:
man 3 fflush
引用:
For input streams, fflush() discards any buffered data that has been
fetched from the underlying file, but has not been consumed by the application.

说的是如果对fflush传入一个输入流,会清除已经从输入流中取出但还没有交给程序的数据

注意红字部分。fflush处理的是已经从输入流中取出的数据,而不是输入流中剩余的数据。而且这数据还不能交给程序,也就是说,对于getchar这种函数,只有其还未返回时,stdin的输入缓冲区才可能有数据,此时调用fflush才会有用
代码:
man 3 stdin
引用:
Note that in case stdin is
associated with a terminal, there may also be input buffering in the
terminal driver, entirely unrelated to stdio buffering. (Indeed, nor‐
mally terminal input is line buffered in the kernel.)
和上面连起来看就更明白了,终端驱动中接收你输入文本的缓冲区就相当于是输入流,和stdin的缓冲区是两回事

而在glibc的文档中,关于fflush的说明如下
http://www.gnu.org/software/libc/manual/html_node/Flushing-Buffers.html
引用:
This function causes any buffered output on stream to be delivered to the file. If stream is a null pointer, then fflush causes buffered output on all open output streams to be flushed.

连输入流都没提到。说明glibc实现中的fflush要么对输入流什么都没干,要么干了些对外部完全没有影响的事

要想实现你所希望的效果,可以用非标准的fpurge()。glibc中的近似实现是__fpurge()。自己去
代码:
man 3 fpurge


原文地址:https://www.cnblogs.com/noble/p/4144028.html