在Linux上递归列出C中的目录

时间:2017-10-19 14:43:45

标签: c linux dirent.h

我需要列出目录中的所有项目并列出任何子目录中的所有项目。我有这个功能:

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

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

1 个答案:

答案 0 :(得分:2)

请在调用后添加测试以检查:

dir = opendir(name);

dir不能为null继续处理它。

您的代码应该是

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