linux c编程疑问之一-----关于open,read

jialejiahi 2010-10-22 09:35:02
先贴代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

#define PERMS 06666
#define DUMMY 0
#define BUFSIZE 1024
int main()
{
char **argv;
char *test = "test.txt";
char *bytest = "testcopy.txt";
int source_fd, target_fd, num;
char iobuffer[BUFSIZE];
argv[1] = test;
argv[2] = bytest;
/*
if(argc != 3)
{
printf("Usage: copy Sourcefile Targetfile\n");
return 1;
}
*/
if(source_fd = open(*(argv+1), O_RDONLY, DUMMY) == -1)
{
printf("Source file open error!\n");
return 2;
}
if((target_fd = open(*(argv + 2), O_WRONLY|O_CREAT, PERMS)) == -1)
{
printf("Target file open error!\n");
return 3;
}

while((num = read(source_fd, iobuffer, BUFSIZE)) > 0)
if(write(target_fd, iobuffer, num) != num)
{
printf("Target file write error!\n");
return 4;
}
close(source_fd);
close(target_fd);
return 0;
}
程序的目的是将test.txt 中的内容复制到testcopy.txt,gcc -g -o copy copy.c(程序名是copy.c)后,gdb copy,单步运行到while((num = read(source_fd, iobuffer, BUFSIZE)) > 0)一句时程序卡住不动,为什么呢,静待高手指点.....
...全文
204 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
bluejays 2010-10-22
  • 打赏
  • 举报
回复
lz既然用了gdb,那就可以在执行read之前看看source_fd的值
(gdb) print source_fd
你会看到他的值是0, 这显然不对. open成功的时候返回值大于2, 失败的时候返回值小于0.

lz知道用gdb单步运行就已经是个很好的开始了,多练练就好了。
bluejays 2010-10-22
  • 打赏
  • 举报
回复
$ gdb copy
(gdb) run test.txt testcopy.txt
这样就可以用argv了
bluejays 2010-10-22
  • 打赏
  • 举报
回复
$ gdb
(gdb) run test.txt testcopy.txt
jialejiahi 2010-10-22
  • 打赏
  • 举报
回复
1楼正解,谢谢!
二楼,三楼也非常感谢,可惜我分数不多。
其实我也知道argv不该这样用的,程序写成这样好难看,其实只是为了调试方便,
初学者,不知道怎么在gdb里给argv赋值,汗!
loveqingjian 2010-10-22
  • 打赏
  • 举报
回复
首先你的argv没有初始化,执行会出Segmentation fault
argv = malloc(sizeof(char *) * 2);//分配两个字符串的空间
然后使用strace看看系统调用的执行过程,可以看到每个系统调用的返回值。
bluejays 2010-10-22
  • 打赏
  • 举报
回复
char **argv; 改成 char *argv[3];
不过,argv可不是这么用的
小魔菇 2010-10-22
  • 打赏
  • 举报
回复
argv[1] = test;
argv[2] = bytest;

argv又没有分配空间来存放指针
还是用这个替换一下吧
char *frompathname = test;
char *topathname = bytest;
bluejays 2010-10-22
  • 打赏
  • 举报
回复
if((source_fd = open(*(argv+1), O_RDONLY, DUMMY)) == -1)
注意运算符优先级,你写的那句相当于
if(source_fd = (open(*(argv+1), O_RDONLY, DUMMY) == -1))

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧