使用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));                                 
                    
             
        while (!qu.empty())
        {
           path_and_depth_t path_and_depth = (order == DEPTH_FIRST) ?qu.back() : qu.front();
           string& file_str(path_and_depth.first);
            int depth= path_and_depth.second;
            if (order== DEPTH_FIRST)
           {
               qu.pop_back();
           }
            else
           {
               qu.pop_front();
           }
           fs::path file(file_str);
            if(fs::exists(file))
           {
               if(fs::is_directory(file))
               {
                   if (include_sub_dirs)
                   {
                      files.push_back(file_str);                     
                   }
                   if (depth <max_depth || max_depth == UNLIMITED_DEPTH)
                   {
                       intnext_depth = depth + 1;
                      fs::directory_iteratorend_iter;
                       for(fs::directory_iteratorfile_itr(file); file_itr != end_iter; ++file_itr)
                      {
                         qu.push_back(path_and_depth_t(fs::system_complete(*file_itr).native_directory_string(),next_depth));                                
                      }
                   }
               }
               else
               {
                  files.push_back(file_str);                  
               }
                    
        }
        return true;
    }

};
0 0
原创粉丝点击