linux下fflush(stdin)的使用问题

100 篇文章 1 订阅
76 篇文章 0 订阅

参考自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


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值