|
|
问题是这样的,我在自己写一个类似于ls的命令。编译之后一切正常,但在我打开目前所在目录是出现了Segmentation fault。反复试验之后发现问题出现在这一段里:
- #include <stdlib.h>
- #include <stdio.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <dirent.h>
- void do_show(DIR *);
- int main(int argv,char *argc[])
- {
- char sg;
- int i = 1;
- DIR *dp;
- if(argv == 1)
- {
- [color=Red] sg = '.';
- if((dp = opendir(&sg)) == NULL){
- perror("opendir1!\n");
- exit(1);
- }
- [/color] do_show(dp);
- }
- else{
- while(argv != 1){
- if((dp = opendir(argc[i])) == NULL){
- perror("opendir2!\n");
- exit(1);
- }
- do_show(dp);
- i++;
- argv--;
- }
- }
- closedir(dp);
- }
- void do_show(DIR *temp_dir)
- {
- struct dirent *dir_rec;
- while((dir_rec = readdir(temp_dir)) !=NULL)
- {
- printf("%s\n",dir_rec->d_name);
- }
- }
复制代码
之后把红色一段改为:
- {
- //sg = '.';
- if((dp = opendir(".")) == NULL){
- perror("opendir1!\n");
- exit(1);
- }
- do_show(dp);
- }
复制代码
问题于是就出来了,opendir的格式是这样的:
- DIR *opendir(const char *name);
复制代码
&sg和char *是同样的类型为何会出现这样的问题,难道说就是因为缺一个'/0'导致的?
菜鸟虚心请教,希望大家别笑话 |
|