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

Recursively list directories in C on Linux

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

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)。谁能帮我弄清楚为什么会出现此错误?

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

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