2012-04-08 140 views
0

我試圖遞歸獲取所有文件和文件夾列表。但我只能獲取文件的子目錄和其中的內部。我無法獲取其中的子目錄內的其他文件夾。 我不知道該怎麼辦呢recursively.I希望大家幫我C目錄和子目錄遞歸

  #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

目錄不是C語言的概念,而是操作系統的概念。請正確標記您的問題,以便我們知道您的問題是關於什麼系統。同樣,如果你看看這個頁面的右邊冒號,你會發現很多問題已經被問到了。在發佈之前你有沒有讀過它們? – 2012-04-08 08:21:45

回答

1

1)在您需要的while循環之後調用closedir(da);reader

2)reader每次調用都需要有您需要連接path

ef->d_name,然後調用讀者的絕對路徑。

3)同樣爲了啓用調試,您應該在調用失敗的readdir之後調用perror

+0

謝謝,但它仍然是相同的,我改變了問題中的代碼,也許我犯了一些錯誤 – 2012-04-08 08:07:57

+0

@AnonSr編輯答案 – keety 2012-04-08 08:29:47

+0

謝謝你問題解決了 – 2012-04-08 09:48:50