C编程打开目录中的目录

时间:2017-10-25 14:58:25

标签: c

#include <dirent.h> 
#include <stdio.h> 
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int program(char* file) {
  DIR *d;
  struct dirent *dir;
  d = opendir(file);
  if (d) {
     while ((dir = readdir(d)) != NULL) {
       if(dir->d_type == DT_DIR) {
         if(opendir(dir->d_name)!=NULL) {
          printf("Open successful!  ");
         }
         printf("Is a dir! ");
       }

       printf("%s\n", dir->d_name);
     }

     closedir(d);
  }

 return(0);

}

让我说我在这样的c程序中访问一个目录,我发现其中一个条目也是一个目录?我如何打开此目录条目?我认为我的代码没有正确执行

1 个答案:

答案 0 :(得分:1)

此代码以递归方式调用函数以列出文件和目录。

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    listdir(".", 0);       //Call the function for the current path
}

/* Function to list files and directories
 * @parameter Name : Name is the path
 * @parameter indent: indentation for printing the files and directories 
                      in the hierarchical structure
 */
void listdir(const char *name, int indent)
{
    DIR *dir;
    struct dirent *entry;

    /* Base Case, return if the current file is not directory */
    if (!(dir = opendir(name)))
        return;

    /*Loop for all the files in the current directory */
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char path[1024];

            /* If the path is . (current path) or .. (parent of the current 
              directory) then continue (do not call  lisdir()), 
              we don't want to stuck in infinite situation!
            */
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
            printf("%*s[%s]\n", indent, "", entry->d_name);

            /* Call the function again for the current path
               Add 2 to indentation, that is to leave 2 more spaces in the 
               hierarchical structure 
            */
            listdir(path, indent + 2);
        } else {
            printf("%*s- %s\n", indent, "", entry->d_name);
        }
    }
    closedir(dir);
}