遍历目录

时间:2010-03-31 03:26:23

标签: c++ boost

有没有办法遍历目录的内容?我想将每个文件夹的名称存储在给定目录中。

谢谢!

1 个答案:

答案 0 :(得分: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";
  }
}