c - 带有读取系统调用的空字符串输入导致段错误

标签 c operating-system segmentation-fault system

我正在尝试使用 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/

相关文章:

c - 使用 gdb 调试从 stdin 读取输入的交互式程序

linux - 一次在 Linux 操作系统上运行的用户总数是多少?

io - 从裸机操作系统导出数据的最简单方法

c - 段错误(核心已转储)。不确定为什么?

c - fork 没有段错误

c - 使用递归查找两个数组是否有公共(public)数字

c - 在 C 中将矩阵作为参数传递不起作用

c++ - inportb() 和 inport() 函数有什么区别?

c - 系统调用 execve 不使用 ls 函数返回

c++ - spoj 中的 SIGSEGV 错误但在 ideone 中工作正常