递归查找子目录和文件

use*_*654 1 c linux filesystems

我想以递归方式检索给定路径中包含的所有文件,目录和子目录.但是当我的代码到达第二级(目录中的目录)时我遇到了问题:它不是打开内部目录来搜索其内容,而是抛出错误.这是我做的:

void getFile(char *path)
{

    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir(path)) != NULL) {
    /* print all the files and directories within directory */
    while ((ent = readdir(dir)) != NULL) {
      if((strcmp(ent->d_name,"..") != 0) && (strcmp(ent->d_name,".") != 0)){

      printf ("%s", ent->d_name);

      if(ent->d_type == DT_DIR){

      printf("/\n");
      getFile(ent->d_name);
      }
      else{

      printf("\n");
      }
      }   // end of if condition
    }     // end of while loop
    closedir (dir);

}
Run Code Online (Sandbox Code Playgroud)

Bas*_*tch 5

使用ftw(3)库函数递归遍历文件树.这是非常标准的.

您也可以查看nftwMUSL libc代码.它非常易读.