2010-03-31 145 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"; 
    } 
} 
采取