如何列出子文件夹中的所有文件?

时间:2014-11-07 15:19:47

标签: c windows

我已经尝试了几天来编写一个代码来检查C:\ Users中的所有子文件夹,并打印他们的文件,例如:

C:\用户\公共

文件

C:\用户\ Somefolder

文件

这是我的代码:

main() {

  DIR *dr,*dirp;
  struct dirent *dr_ent,*sec; 
  char *buf,*baf; 
  char get[50],x[50];     
  char folder[] = "C:\\Users\\"; 

  dr = opendir(folder);
  if (dr != NULL) 
   goto next;
  else return -1;

  next:
       while ((dr_ent = readdir(dr))!=NULL) {
             buf=dr_ent->d_name;
             strcpy(get,buf);
             if (strstr(get,".")==NULL && strstr(get,"..")==NULL) { 
                strcpy(x,folder);
                strcat(x,get); 
                printf("%s\n",x);
                continue;
                goto read;
                Sleep(300);
             }
       }
  read: 
       dirp = opendir(get);
       while ((sec = readdir(dirp))!=NULL) {
             baf=sec->d_name;
             printf("%s\n",baf);
             Sleep(300);
       }       


  system("PAUSE");
  return EXIT_SUCCESS;
  }`enter code here`

在这种情况下,只读取了一个文件夹。所以我实际上是通过从循环中取一个变量来犯错误所以只有一行被采用了?为什么第二个标签被程序完全忽略了?顺便说一句,我是C编程的初学者,所以不要对潜在的错误感到惊讶。

1 个答案:

答案 0 :(得分:1)

第二个标签被完全忽略,因为在goto read;使用continue;之前,它会带您进入while循环的下一次迭代,忽略其后的所有其他内容。

同样在您的代码中,您不会检查目录的条目是文件还是目录来正确处理它。我的意思是你应该进入一个目录,但是当你遇到一个文件时,你应该打印一个文件的名字。(正如你所做的那样)。

你可以使用递归函数来避免使用goto,因为goto是一种不好的做法。

void list_dir(char const* dirName)
{
    DIR* dir;

    if ((dir = opendir(dirName)) == NULL) {
        fprintf(stderr, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
        exit(EXIT_FAILURE);
    }

    struct dirent* entry;

    // For every entry in the directory
    while ((entry = readdir(dir)) != NULL) {
        char* path;                         // path =  dirName/entryName
        int pathLength;                     // length of the path in chars
        struct stat entryStats;             // info of the entry
        char* entryName = entry->d_name;    // entry filename

        pathLength = strlen(dirName) + 1 + strlen(entryName);
        path = malloc((pathLength + 1) * sizeof(char));
        strcpy(path, dirName);
        strcat(path, "/");
        strcat(path, entryName);

        if (stat(path, &entryStats) == 0) {                
            // If the entry is a directory
            if (entryStats.st_mode & S_IFDIR) {
                // If the directory is not "." or ".." get its entries
                if (strcmp(entryName, ".") != 0 &&
                        strcmp(entryName, "..") != 0) {
                    list_dir(path);
                }
            }
            // If the entry is a file
            else if (entryStats.st_mode & S_IFREG) {
                printf("%s\n",path);
            }
        }
        free(path);
    }
    closedir(dir);
}

上述代码适用于Unix,但在Windows上,如果您使用的是Visual Studio,则可能需要将statstruct stat更改为_statstruct _stat