recursive folder scanning in c++

前端 未结 6 466
小鲜肉
小鲜肉 2020-12-07 23:45

I want to scan a directory tree and list all files and folders inside each directory. I created a program that downloads images from a webcamera and saves them locally. This

6条回答
  •  萌比男神i
    2020-12-08 00:06

    I'm old school, no ftw() for me! This is crude (it's been a while since I did straight C programming), and lots of stuff is hardcoded, and I probably messed up my length calculations for the strnc*() functions, but you get the idea. There's a similar example in K&R btw.

    #include 
    #include 
    #include 
    
    #include 
    #include 
    
    void listdir(char* dirname, int lvl);
    
    int main(int argc, char** argv)
    {
    
      if (argc != 2) {
        fprintf(stderr, "Incorrect usage!\n");
        exit(-1);
      }
      listdir(argv[1], 0);
    
    
      return 0;
    }
    
    void listdir(char* dirname, int lvl)
    {
    
      int i;
      DIR* d_fh;
      struct dirent* entry;
      char longest_name[4096];
    
      while( (d_fh = opendir(dirname)) == NULL) {
        fprintf(stderr, "Couldn't open directory: %s\n", dirname);
        exit(-1);
      }
    
      while((entry=readdir(d_fh)) != NULL) {
    
        /* Don't descend up the tree or include the current directory */
        if(strncmp(entry->d_name, "..", 2) != 0 &&
           strncmp(entry->d_name, ".", 1) != 0) {
    
          /* If it's a directory print it's name and recurse into it */
          if (entry->d_type == DT_DIR) {
            for(i=0; i < 2*lvl; i++) {
              printf(" ");
            }
            printf("%s (d)\n", entry->d_name);
    
            /* Prepend the current directory and recurse */
            strncpy(longest_name, dirname, 4095);
            strncat(longest_name, "/", 4095);
            strncat(longest_name, entry->d_name, 4095);
            listdir(longest_name, lvl+1);
          }
          else {
    
            /* Print some leading space depending on the directory level */
            for(i=0; i < 2*lvl; i++) {
              printf(" ");
            }
            printf("%s\n", entry->d_name);
          }
        }
      }
    
      closedir(d_fh);
    
      return;
    }
    

提交回复
热议问题