gpt4 book ai didi

c - 如果返回 NULL,则由 fgets 保证空终止

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

在阅读 C99 草案时 ISO/IEC 9899:TC2 WG14/N1124 , 我偶然发现了一些令我担心的陈述:

如果 fgets 返回 NULL,提供给 fgets 的字符串/缓冲区是否也保证以 null 终止?

§7.19.7.2 说明中的状态

A null character is written immediately after the last character read into the array.

但在返回下:

If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.

因此,在我的解释中,最后一个陈述暗示在任何返回 NULL 的情况下都不会给出此保证。我已经要更正了 http://en.cppreference.com ,因为他们正在使用 errnofgets 没有义务设置。但我不确定我是否误解了这一点。

最佳答案

您正确解读了标准。如果出现错误,该函数将返回 NULL,并且缓冲区的内容不可信。

这允许 fgets 直接读入目标缓冲区,中间没有任何双缓冲区。因此,如果在预期数据中途出错,它可能会简单地停止并返回 NULL。

还要注意这个特殊情况 (7.21.7.2):

If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned.

关于c - 如果返回 NULL,则由 fgets 保证空终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35868355/

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