2017-10-19 43 views
0

我需要列出目录中的所有项目并列出所有子目录中的所有项目。我有这个功能:递归列出Linux中C上的目录

void rls_handler(const char *name, int indent){ 
DIR *dir; 
struct dirent *sd; 
dir = opendir(name); 
while((sd = readdir(dir)) != NULL){ 
    if(sd->d_type == DT_DIR){ //if item is a directory, print its contents 
     char path[1024]; 
     if((strcmp(sd->d_name, ".")) !=0 && (strcmp(sd->d_name, "..")) != 0){ //skip '.' and '..' 
      printf("%*s[%s]\n",indent,"",sd->d_name); 
      rls_handler(path,indent+2); //recurse through rls_handler with subdirectory & increase indentation 
    }else{ 
     continue; 
    }  
    }else{ 
    printf("%*s- %s\n",indent, "", sd->d_name); 
    } 
}//end while 
closedir(dir); 
}//end rls_handler 

我得到一个segfault在行:while((sd = readdir(dir)) != NULL)。任何人都可以帮我弄清楚为什么我得到这个错误?

+0

检查只是段错误之前,什么是在'dir'。 – Neo

+0

'rls_handler(path,indent + 2);' '路径'使用未初始化。 –

回答

2

请调用后添加一个测试来检查:

dir = opendir(name); 

dir是不是空来继续工作。

你的代码看起来应该像

dir = opendir(name); 
if (dir!=NULL) 
{ 
while((sd = readdir(dir)) != NULL){ 
... 
} //end while 
closedir(dir); 
} // end if dir not NULL 
}//end rls_handler