2010-03-31 177 views
2

有什麼方法可以遍歷目錄的內容?我想將每個文件夾的名稱存儲在給定的目錄中。遍歷目錄

謝謝!

回答

7

根據你對C++/Boost感興趣的標籤。然後,請從this SO answer借款:

#include <utility> 
#include <boost/filesystem.hpp> 
#include <boost/foreach.hpp> 

#define foreach BOOST_FOREACH 
namespace fs = boost::filesystem; 

fs::recursive_directory_iterator it(top), eod; 
foreach (fs::path const & p, std::make_pair(it, eod)) { 
    if (is_directory(p)) { 
     ... 
    } else if (is_regular_file(p)) { 
     ... 
    } else if (is_symlink(p)) { 
     ... 
    } 
} 

另一個版本,從Rosetta code:

#include "boost/filesystem.hpp" 
#include "boost/regex.hpp" 
#include <iostream> 

using namespace boost::filesystem; 

int main() 
{ 
    path current_dir("."); // 
    boost::regex pattern("a.*"); // list all files starting with a 
    for (recursive_directory_iterator iter(current_dir), end; 
     iter != end; 
     ++iter) 
    { 
    std::string name = iter->path().leaf(); 
    if (regex_match(name, pattern)) 
     std::cout << iter->path() << "\n"; 
    } 
} 
採取