我正在尝试使用 read(int fd, void *buf, size_t count);
从 STDIN 读取输入
当输入是 EOF 时,我应该如何处理?还是空字符串?目前,我遇到了段错误
这是代码片段:
int rd;
char buf[100];
rd = read(0, buf, 99);
buf[strcspn(buffer, "\n")] = 0;
谢谢
最佳答案
与所有其他字符串函数一样,strcspn
依赖于以 null 结尾的字符串开头。
如果输入不包含换行符,则 strcspn
函数将由于缺少终止符而越界。
您还需要处理 read
返回文件结尾或错误的情况,这由返回 0
或 -1< 表示
(分别)。正如指定的那样 in the manual (你真的应该读一读!)。
只需在 read
调用后的适当位置直接添加终止符,但前提是 read
成功:
rd = read(STDIN_FILENO, buf, sizeof buf - 1); // sizeof buf relies on buf being an actual array and not a pointer
if (rd == -1)
{
// Error, handle it
}
else if (rd == 0)
{
// End of file, handle it
}
else
{
// Read something
buf[rd] = '\0'; // Terminate string
// Terminate a newline
buf[strcspn(buf, "\n")] = '\0'; // Truncate at newline (if any)
}
关于c - 带有读取系统调用的空字符串输入导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54346410/