使用boost::filesystem实现目录遍历
来源:互联网 发布:直播弹幕语音助手 mac 编辑:程序博客网 时间:2024/06/04 19:50
下面的代码实现了深度优先和广度优先两种遍历方式,可以指定最大遍历深度,可以指定结果中是否包含子文件夹
======================================================================
#include <string>
#include <vector>
#include <deque>
#include <utility>
#include<boost/filesystem/operations.hpp>
#include<boost/filesystem/path.hpp>
class file_tool
{
public:
enum traverse_order_t
{
DEPTH_FIRST = 1,
BREADTH_FIRST =2,
};
enum { UNLIMITED_DEPTH =-1};
static bool get_sub_files(conststd::string& path,std::vector<std::string>&files, int max_depth = UNLIMITED_DEPTH, bool include_sub_dirs =false, traverse_order_t order = BREADTH_FIRST)
{
using namespace std;
namespace fs =boost::filesystem;
typedefstd::pair<string,int> path_and_depth_t;
deque<path_and_depth_t> qu;
{
fs::path root(path);
if(!fs::exists(root) ||!fs::is_directory(root))
{
return false;
}
if(max_depth <= 0 &&max_depth != UNLIMITED_DEPTH)
{
return true;
}
fs::directory_iteratorend_iter;
for(fs::directory_iteratorfile_itr(root); file_itr != end_iter; ++file_itr)
{
qu.push_back(path_and_depth_t(fs::system_complete(*file_itr).native_directory_string(),1));
}
======================================================================
#include <string>
#include <vector>
#include <deque>
#include <utility>
#include<boost/filesystem/operations.hpp>
#include<boost/filesystem/path.hpp>
class file_tool
{
public: