您的位置:首页 > 其它

使用boost::filesystem实现目录遍…

2015-10-10 09:20 344 查看
下面的代码实现了深度优先和广度优先两种遍历方式,可以指定最大遍历深度,可以指定结果中是否包含子文件夹

======================================================================

#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(const
std::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;

        typedef
std::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_iterator
end_iter;

            for
(fs::directory_iterator
file_itr(root); file_itr != end_iter; ++file_itr)

           
{

           
   
qu.push_back(path_and_depth_t(fs::system_complete(*file_itr).native_directory_string(),
1));           
           
           

           
}     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: