ash*_*bhy 1 c linux simulation
我试图在Red Hat Linux中模拟cat命令.我运行程序时出现分段错误.
例如:
./a.out a > b
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
为什么我会收到分段错误?
我有一个类似的程序,我打开并以相同的方式创建文件,该程序正在运行,但这个给我一个分段错误.
这可能是因为重定向是由shell处理的,而不是由你的程序处理的,所以argv[2]是NULL和argv[3]不存在.
但是,您应该使用调试器来查找实际发生的情况.然后添加适当的错误检查.
| 归档时间: |
|
| 查看次数: |
2340 次 |
| 最近记录: |