2014-10-17 257 views
0

我正在嘗試從文件夾中讀取所有txt文件,包括使用C++選定文件夾的子目錄中的txt文件。如何讀取文件夾中的所有txt文件? (包括子文件夾)

我實現了該程序的一個版本,它讀取特定文件夾中的所有文本文件,但不會迭代到所有子文件夾。

#include "stdafx.h" 
#include <iostream> 
#include <fstream> 
#include <iterator> 
#include <string> 
#include <dirent.h> 

using namespace std; 

int main() { 

    DIR*  dir; 
    dirent* pdir; 

    dir = opendir("D:/");  // open current directory 

    int number_of_words=0; 
    int text_length = 30; 
    char filename[300]; 
    while (pdir = readdir(dir)) 
    { 
     cout << pdir->d_name << endl; 
     strcpy(filename, "D:/..."); 
     strcat(filename, pdir->d_name); 
     ifstream file(filename); 
     std::istream_iterator<std::string> beg(file), end; 

     number_of_words = distance(beg,end); 

     cout<<"Number of words in file: "<<number_of_words<<endl; 
     ifstream files(filename); 
     char output[30]; 
     if (file.is_open()) 
     { 
      while (!files.eof()) 
      { 
        files >> output; 
        cout<<output<<endl; 
      } 
     } 
     file.close(); 
    } 
    closedir(dir); 
    return 0; 
} 

我應該修改該程序以在所選文件夾的子文件夾中搜索txt文件嗎?

+0

,看一下[提高文件系統(http://www.boost.org/doc/libs/1_56_0/libs/filesystem/doc/tutorial。 HTML) – 2014-10-17 08:50:22

回答

0

我在這裏找到一種方法來檢查文件是否是一個目錄:Accessing Directories in C

你應該做的首先是把你的代碼的函數裏面,可以說,無效F(字符*目錄),從而使您可以處理多個文件夾。然後使用上述鏈接中提供的代碼來查找文件是否是目錄。

如果它是一個目錄,請調用f,如果它是一個txt文件,請執行你想要的操作。

要小心一件事:每個目錄中都有一些目錄會將您發送到無限循環。 「」指向你的當前目錄,「..」指向父目錄,「〜」指向主目錄。你可能想要排除這些。 http://en.wikipedia.org/wiki/Path_%28computing%29

0

最簡單的方法是編寫一個read_one_file()函數,並遞歸調用它。

read_one_file()看起來是這樣的:

read_one_file(string filename){ 
    if(/* this file is a directory */){ 
     opendir(filename); 
     while(entry=readdir){ 
      read_one_file(/*entry's filename*/); 
     } 
    }else{ /* this file is a regular file */ 
     /* output the file */ 
    } 
} 
相關問題