gpt4 book ai didi

c - 运行我的 C 程序时在 Linux 中出现段错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:15 25 4
gpt4 key购买 nike

我正在尝试模拟 cat命令 Red Hat Linux .我得到一个 segmentation fault当我运行我的程序时。

例如:

./a.out a > b

a 包含你好。我希望 hello 被复制到 b 中。

我的代码如下:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main(int argc,char *argv[])
{
int f, fd, r;
char buf[100];

if (argc < 2)
{
printf("Error");
return 0;
}
else
{
if (!strcmp(argv[2],">"))
{
f = open(argv[1],0,00777);

if (f == -1)
printf("no file");
else
{
fd = creat(argv[3],00777);
while( (r = read(f,buf,50)) > 0)
write(fd, buf, r);
}
}
}
return 0;
}

为什么会出现段错误?

我有一个类似的程序,我以相同的方式打开和创建文件,并且该程序正在运行,但这个程序给我一个段错误。

最佳答案

可能是因为重定向是由 shell 而不是你的程序处理的,所以 argv[2]NULLargv[3]不存在。

然而,您应该使用调试器来找出真正发生的事情。然后添加适当的错误检查。

关于c - 运行我的 C 程序时在 Linux 中出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304595/

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