gpt4 book ai didi

c - fgets 和错误处理的小麻烦

转载 作者:太空狗 更新时间:2023-10-29 16:01:45 24 4
gpt4 key购买 nike

我最近开始学习C,遇到了一个代码被截断的小问题。

我想要通过 stdin 读取一个 20 个字符长的字符串,所以我选择了 fgets。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
unsigned int length = 20;
char input_buffer[length];
fgets(input_buffer, length, stdin);
if(input_buffer == NULL)
printf("Error, input too long");
else
printf("%s", input_buffer);
return 0;
}

它编译没有任何错误,如果我输入一个短于 20 个字符的句子,一切都很好。但是当我尝试测试错误处理时,它失败了。

输出是:

peter@antartica ~/test % ./test    
Hello world, this is a very long test
Hello world, this i%

我做错了什么吗?我以为 fgets 会在失败时返回 NULL 指针(这里应该是这种情况)?

感谢您的帮助。

最佳答案

来自 fgets reference :

On success, the function returns str.

If the end-of-file isencountered while attempting to read a character, the eof indicator isset (feof). If this happens before any characters could be read, thepointer returned is a null pointer (and the contents of str remainunchanged).

If a read error occurs, the error indicator (ferror) isset and a null pointer is also returned (but the contents pointed bystr may have changed).

因此它可能会返回 NULL 而不会在到达文件末尾时产生错误。您可能需要查看 ferror 返回值才能确定。

请注意 fgets() 会自动在字符串末尾附加一个空字符 (\0),这可能会导致字符串被截断,因为您指定必须读取多少个字符。如果找到超过 length 个字符的字符串,调用不会失败。

关于c - fgets 和错误处理的小麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22336331/

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