【发布时间】:2013-04-24 15:37:22
【问题描述】:
我正在尝试在Red Hat Linux 中模拟cat 命令。我运行程序时收到segmentation fault。
例如:
./a.out a > b
a 包含你好。我希望你好被复制到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;
}
为什么会出现分段错误?
我有一个类似的程序,我在其中以相同的方式打开和创建文件,并且该程序正在运行,但是这个程序给了我一个分段错误。
【问题讨论】:
-
gdb被发明的众多原因之一。 -
@WhozCraig - 现在,如果他们只能继续讨论 gdb 需要改进并变得更加易用和友好的众多原因之一。
-
不要浪费你的生命手工格式化代码;使用计算机程序。 en.wikipedia.org/wiki/Indent_(Unix)
-
@Duck 所有主要的 IDE 都对 GDB 有很好的支持,包括调用堆栈和变量的可视化处理。
-
然后
gdb与-g组合在你的编译命令行参数上会非常方便。
标签: c linux simulation