如何在标准C++中递归地遍历每个文件/目录?
发布于 2008-09-15 21:44:43
在标准C++中,由于标准C++没有目录的概念,从技术上讲没有办法做到这一点。如果你想扩展一下你的网络,你可能会考虑使用Boost.FileSystem。这已经被接受为包含在TR2中,所以这为您提供了最好的机会,使您的实现尽可能接近标准。
下面是一个直接取自网站的例子:
bool find_file( const path & dir_path, // in this directory,
const std::string & file_name, // search for this name,
path & path_found ) // placing path here if found
{
if ( !exists( dir_path ) ) return false;
directory_iterator end_itr; // default construction yields past-the-end
for ( directory_iterator itr( dir_path );
itr != end_itr;
++itr )
{
if ( is_directory(itr->status()) )
{
if ( find_file( itr->path(), file_name, path_found ) ) return true;
}
else if ( itr->leaf() == file_name ) // see below
{
path_found = itr->path();
return true;
}
}
return false;
}
发布于 2015-10-01 21:55:00
从C++17、标头和range-for
开始,您可以简单地执行以下操作:
#include <filesystem>
using recursive_directory_iterator = std::filesystem::recursive_directory_iterator;
...
for (const auto& dirEntry : recursive_directory_iterator(myPath))
std::cout << dirEntry << std::endl;
从C++17开始,std::filesystem
是标准库的一部分,可以在<filesystem>
头文件中找到(不再是“实验性的”)。
发布于 2013-10-18 23:11:33
使用新的基于for
和Boost的C++11范围,您可以使它变得更加简单
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
struct recursive_directory_range
{
typedef recursive_directory_iterator iterator;
recursive_directory_range(path p) : p_(p) {}
iterator begin() { return recursive_directory_iterator(p_); }
iterator end() { return recursive_directory_iterator(); }
path p_;
};
for (auto it : recursive_directory_range(dir_path))
{
std::cout << it << std::endl;
}
https://stackoverflow.com/questions/67273
复制相似问题