gpt4 book ai didi

c - 当我使用 fgets 作为输入函数时如何检测文件结尾?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:44 25 4
gpt4 key购买 nike

if (fgets(string, 35, stdin)==NULL)

它只在我使用 ctrl+D 时有效。

它会打印

"what I want"

然后退出。

但是,如果我输入

'abc'

并且不要按 Enter,然后按 ctrl+D

不行,继续运行,直到我第二次用ctrl+D

你能给我一些想法吗?

最佳答案

这是正常行为 - 当您在已经在该行中输入了一些字符后输入它时,它允许进程读取您输入的字符(您会注意到您不能退格超过这一点,如果你在 cat 中这样做你输入的字符可能会立即回显)

The relevant Unix standard can be found here :

EOF

Special character on input, which is recognized if the ICANON flag is set. When received, all the bytes waiting to be read are immediately passed to the process without waiting for a < newline >, and the EOF is discarded. Thus, if there are no bytes waiting (that is, the EOF occurred at the beginning of a line), a byte count of zero shall be returned from the read(), representing an end-of-file indication. If ICANON is set, the EOF character shall be discarded when processed.

基本上,行中间的 ctrl-D 并不是“真正的”文件结尾,没有理由期望检测到它。如果你想在没有最终换行符的情况下结束标准输入,只需按两次 ctrl-D。

关于c - 当我使用 fgets 作为输入函数时如何检测文件结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32132109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com