stdin 上的 close/fclose 是否保证正确?
似乎以下调用执行了您所期望的操作(关闭流并不允许任何进一步的输入 - 等待流上的输入的任何操作都会返回错误),但它是否保证在所有编译器/平台上都是正确的?
close(fileno(stdin));
fclose(stdin);
It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?
close(fileno(stdin));
fclose(stdin);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fclose(stdin)
会导致进一步使用stdin
(隐式或显式)来调用未定义的行为,这是一件非常糟糕的事情。 它不会“禁止输入”。close(fileno(stdin))
导致在当前缓冲区耗尽后,从stdin
输入的任何进一步尝试都会失败,并显示EBADF
,但只有在您打开另一个文件之前,该文件将成为 fd #0 并且会发生不好的事情。更稳健的方法可能是:
添加一些错误检查。 这将确保所有读取(在当前缓冲区耗尽后)都会导致错误。 如果您只是希望它们导致 EOF,而不是错误,请使用
O_RDONLY
而不是O_WRONLY
。fclose(stdin)
causes any further use ofstdin
(implicit or explicit) to invoke undefined behavior, which is a very bad thing. It does not "inhibit input".close(fileno(stdin))
causes any further attempts at input fromstdin
, after the current buffer has been depleted, to fail withEBADF
, but only until you open another file, in which case that file will become fd #0 and bad things will happen.A more robust approach might be:
with a few added error checks. This will ensure that all reads (after the current buffer is depleted) result in errors. If you just want them to result in EOF, not an error, use
O_RDONLY
instead ofO_WRONLY
.不要关闭 fileno(FILE*)。 FILE 是一个缓冲对象。 研究其实现并干预其状态会带来所有其他软件模块上类似不当行为所带来的警告和危险。
不要这样做。
啊。 严重地。 可恶的。
DO NOT DO a close on fileno(FILE*). FILE is a buffering object. Looking into its implementation and meddling with its state carries all the caveats and dangers that would come with similar misbehavior on any other software module.
Don't do it.
AGH. Seriously. Nasty.
没有什么能保证在所有可能的操作系统上都是正确的。 但是,调用 fclose(stdin) 可以在任何 POSIX 兼容操作系统以及 Windows 操作系统上运行,因此您目前应该可以使用几乎所有常用的命令。
正如前面的答案和我的评论所述,不需要在文件句柄上调用 close 。 fclose() 将正确地为您关闭所有内容。
Nothing is guaranteed correct across every possible operating system. However, calling fclose(stdin) will work on any POSIX compliant operating system as well as Windows operating systems, so you should hit pretty much anything in general use at the moment.
As stated by the previous answer as well as my comment, there is no need to call close on the file handle. fclose() will properly close everything down for you.