简体   繁体   English

递归查找子目录和文件

[英]Recursively find subdirectories and files

I want to retrieve all the files, directories and subdirectories contained within a given path, recursively. 我想递归地检索给定路径中包含的所有文件,目录和子目录。 But I have a problem when my code reaches the second level (a directory within a directory): instead of opening the inner directory to search its contents, it throws an error. 但是,当我的代码到达第二级(目录中的目录)时,我遇到了一个问题:它没有打开内部目录来搜索其内容,而是引发了错误。 Here is what I have done: 这是我所做的:

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);

}

Use the ftw(3) library function to recursively walk a file tree. 使用ftw(3)库函数以递归方式遍历文件树。 It is quite standard. 这是很标准的。

You may also look into nftw and the MUSL libc source code for it . 您也可以查看nftwMUSL libc代码 It is quite readable. 这是很可读的。

When you recursively call getFile you only call it with the only the name of the directory you just read. 递归调用getFile ,仅使用您刚刚读取的目录名称来调用它。 It's not the full path, which is what you need. 不是您需要的完整路径。 You have to manage that yourself. 您必须自己进行管理。


Something like this: 像这样:

if(ent->d_type == DT_DIR)
{
    if ((strlen(path) + strlen(ent->d_name) + 1) > PATH_MAX)
    {
        printf("Path to long\n");
        return;
    }

    char fullpath[PATH_MAX + 1];

    strcpy(fullpath, path);
    strcat(fullpath, "/");
    strcat(fullpath, ent->d_name); // corrected

    getFile(fullpath);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM