2016-12-24 93 views
-3

例如特定擴展名:.txt文件計數的文件與目錄和子目錄C++

C:\Duck\aa.txt 
C:\Duck\Dog\Pig\cc.txt 
C:\Duck\Dog\kk.txt 
C:\Duck\Cat\zz.txt 
C:\xx.txt 

返回5

+1

在尋求幫助時,最好提供已嘗試的代碼和遇到的錯誤。要求社區爲你寫代碼是不客觀的。 –

+3

這個問題表明您無法自行找到解決方案,包括在發佈之前無法通過Google或本網站進行基本搜索。在目前的狀態下,它對未來的讀者絕對沒有價值,應該關閉。 –

+0

我得到的最多的是我的答案中的代碼。抱歉,以前沒有顯示我的代碼,是的,我已經搜索過,但我找不到在count中的子目錄中包含.txt的方法,但我已經在Dac Saunders的幫助下管理。謝謝你們。 – Tito

回答

0

必須使用opendir()readdir()

例子:

DIR *dir = opendir("."); // current dir 
if (dir == NULL) { 
    perror("opendir: ."); 
    return 1; 
} 

struct dirent *dirent; 
while ((dirent = readdir(dir)) != NULL) { 
    printf("%s\n", dirent->d_name); 
} 

closedir(dir); 
-1

請您嘗試一下。

#include <sys/types.h> 
#include <dirent.h> 
#include <stdio.h> 
#include <string.h> 
int count = 0; 
void listdir(const char *name, int level) 
{ 

    DIR *dir; 
    struct dirent *entry; 
    if (!(dir = opendir(name))) 
     return; 
    if (!(entry = readdir(dir))) 
     return; 

    do { 
     if (entry->d_type == DT_DIR) { 
      char path[1024]; 
      int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name); 
      path[len] = 0; 
      if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) 
       continue; 
      listdir(path, level + 1); 
     } 
     else { 
      const char *ext = strrchr(entry->d_name,'.'); 
      if((!ext) || (ext == entry->d_name)) 
       ; 
      else { 
       if(strcmp(ext, ".txt") == 0) { 
        printf("%*s- %s\n", level * 2, "", entry->d_name); 
        count++; 
       } 
      } 

     } 
    } while (entry = readdir(dir)); 
    closedir(dir); 

} 

int main(void) 
{ 
    listdir(".", 0); 
    printf("There are %d .txt files in this directory and its subdirectories\n", count); 
    return 0; 
} 

測試

./a.out 
- hi.txt 
- payfile.txt 
- csis.txt 
- CMakeCache.txt 
- text.txt 
- sorted.txt 
- CMakeLists.txt 
- ddd.txt 
- duom.txt 
- output.txt 
     - mmap_datafile.txt 
     - file_datafile.txt 
    - CMakeLists.txt 
    - link.txt 
    - TargetDirectories.txt 
There are 15 .txt files in this directory and its subdirectories 
-1

謝謝大家的回答,您曾試圖代碼:

WIN32_FIND_DATA fdata; 
int counter = 0; 
if (HANDLE first = FindFirstFile(L"C:\\duck\\*.txt", &fdata)) 
{ 
    counter++; 
    do 
    { 
     counter++; 
    } while (FindNextFile(first, &fdata)); 
} 

但你可以用同樣的看,我沒有得到結果我正在尋找,其中包括子目錄。 感謝「Dac Saunders」和所有其他人,這對我們有很大的幫助。

+0

請參加[旅遊]。如果你自己回答你的問題。答案需要是一個解決方案。你的回答很糟糕,因爲我不明白你的英文,你說[「我得到的最多的是我的答案中的代碼。」](http://stackoverflow.com/questions/41309872/count-files-在特定的擴展名在目錄和子目錄C/41309928#comment69834928_41309872)顯然這個代碼是行不通的。如果你想添加代碼,你可以試試[編輯](http://stackoverflow.com/posts/41309872/edit)你的問題,並刪除這個答案。或者用你的最終解決方案來編輯​​這個答案。 – Stargateur