简体   繁体   中英

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. It is quite standard.

You may also look into nftw and the MUSL libc source code for it . It is quite readable.

When you recursively call getFile you only call it with the only the name of the directory you just read. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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