遍历目录

jc.*_*jc. 2 c++ boost

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

谢谢!

Eli*_*sky 7

根据您对C++/Boost感兴趣的标签.然后,请从这个SO答案中借鉴:

#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)) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个版本取自Rosetta代码:

#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";
  }
}
Run Code Online (Sandbox Code Playgroud)