C目录和子目录递归

时间:2012-04-08 07:33:34

标签: c directory

我试图以递归方式获取所有文件和文件夹列表。但我只能获取文件的子目录及其内部。我无法获取子目录内的其他文件夹。 我不知道如何递归。我希望你帮助我

          #include <stdio.h>
     #include <sys/types.h>
     #include <dirent.h>
     #include <windows.h>
     #include <unistd.h>
     #include <string.h>
     void list(char *a);
     void reader(char *path);   
     int
     main (void)
     {
       DIR *dp;
       struct dirent *ep;

       dp = opendir ("C:\\Users\\pen\\Documents\\");
       if (dp != NULL)
         {
           while (ep = readdir (dp)){

GetFileAttributes(ep->d_name); 
if(FILE_ATTRIBUTE_DIRECTORY & GetFileAttributes(ep->d_name))
{

        if (strcmp(".",ep->d_name)==0)
            continue;

    if (strcmp("..",ep->d_name)==0)
    continue;



     reader(ep->d_name);

}

             }
             closedir(dp);

         }
       else
         perror ("Couldn't open the directory");
         closedir(dp);
     system("pause");
       return 0;
     }
    void reader(char *path){
            DIR *da;
            struct dirent *ef;
                da = opendir(path);
            while (ef=readdir(da)){
            printf ("%s\n",ef->d_name);
        if(FILE_ATTRIBUTE_DIRECTORY & GetFileAttributes(ef->d_name))
        {

if (strcmp(".",ef->d_name)==0)
continue;


    if (strcmp("..",ef->d_name)==0)
continue;
    reader(ef->d_name);

}
    }
      closedir(da);
}

1 个答案:

答案 0 :(得分:1)

1)在reader中,您需要在while循环后调用closedir(da);

2)每次调用reader都需要有连接所需的绝对路径path

ef->d_name,然后给读者打电话。

3)为了启用调试,您应在perror电话失败后致电readdir

相关问题