- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我最近开始学习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/
在实现特定的排序算法时,我遇到了一个连 Google 都不想帮助我的问题...首先关于算法的一些话: 最重要的是将输入(数组)分成三部分:选择两个关键数字(红色和蓝色,断言红色 = 3 的分区由一个键
我是一名优秀的程序员,十分优秀!