LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1196|回复: 7

linux系统编程时遇到的问题,关于"段错误"

[复制链接]
发表于 2006-10-18 18:01:39 | 显示全部楼层 |阅读模式
刚开始学习系统编程,希望大家多多指教!

编写cp命令的代码如下:

      1 /* cp1.c --version 1 of cp
      2  *        -uses read and write with tunable buffer size
      3  *        -usage: cp1 src dest
      4  */
      5
      6 #include<stdio.h>
      7 #include<fcntl.h>
      8 #include<unistd.h>
      9
     10 #define BUFFERSIZE 4096
     11 #define COPYMODE 0644
     12
     13 void oops(char*,char*);
     14
     15 int main(int argc,char *argv[])
     16 {
     17         int in_fd,out_fd,n_chars;
     18         char buf[BUFFERSIZE];
     19         if(argc != 3){                                //check args
     20                 fprintf(stderr,"usage: %s source destination\n",*argv);
     21                 exit(1);
     22         }
     23         if((in_fd = open(argv[1],O_RDONLY)) == -1)
     24                 oops("Cannot open",argv[1]);
     25
     26         if((out_fd = creat(argv[2],COPYMODE)) == -1)
     27                 oops("Cannot create",argv[2]);
     28
     29         while((n_chars = read(in_fd,buf,BUFFERSIZE)) > 0){
     30                 if(write(out_fd,buf,n_chars) != n_chars)
     31                         oops("write error to",argv[2]);
     32         }
     33
     34         if(n_chars == -1)
     35                 oops("read error from",argv[1]);
     36
     37         if(close(in_fd)==-1 || close(out_fd)==-1)
     38                 oops("error closing file","");
     39 }
     40
     41 void oops(char*s1,char*s2)
     42 {
     43         fprintf(stderr,"Error: %s",s1);
     44         ferror((FILE*)s2);
     45         exit(1);
     46 }


如果44行的ferror中不用FILE*强制转换的话,就会出现

cp1.c: In function `oops':
cp1.c:44: warning: passing arg 1 of `ferror' from incompatible pointer type

用了FILE*的话虽然不会出现编译的警告,但是执行时不能到预期效果.

例如: #./cp1  xx  file
本来应该出现Cannot open xx: NO such file or directory 才对
但是出来的却是Cannot open段错误

是不是因为argv[1]的参数没有传过去?
呵呵!初学,对gdb又不熟,希望大家指点一下,谢谢了`-`
发表于 2006-10-19 11:33:28 | 显示全部楼层
ferror的原型:
int ferror(FILE *stream);
回复 支持 反对

使用道具 举报

发表于 2006-10-19 12:37:45 | 显示全部楼层
汗!

楼主不知道FILE *和char *的区别么?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-10-19 21:24:52 | 显示全部楼层
不知道啊!呵呵!
我只知道FILE*是库函数里定义的一个数据类型.
但是ferror()的确是可以接受字符串的,应该.
希望不吝赐教!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-10-19 22:14:41 | 显示全部楼层
恩  刚才又试了一下,用strerror(errno)处理错误,成功了,呵呵!
要赶紧忘下看了!段错误!与进程有关吧!
回复 支持 反对

使用道具 举报

发表于 2006-10-21 10:25:22 | 显示全部楼层
Post by mynamewsy
不知道啊!呵呵!
我只知道FILE*是库函数里定义的一个数据类型.
但是ferror()的确是可以接受字符串的,应该.
希望不吝赐教!

你还是再复习一下C语言中的指针吧
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-10-22 19:22:46 | 显示全部楼层
我们还真没学过c ,呵呵!
直接学的c++,那我是要看看了
回复 支持 反对

使用道具 举报

发表于 2006-10-23 09:43:34 | 显示全部楼层
使用空指针,就是这种错误
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表