簡體   English   中英

一種使用boost和c ++列出目錄和子目錄中所有文件的方法

[英]A method to list all files in directory and sub-directories using boost and c++

我有以下代碼來搜索目錄及其所有子目錄中的所有文件。 該代碼對嵌套子目錄使用遞歸。

#include "boost/filesystem.hpp"
#include <iostream>

using namespace boost::filesystem;

void getDirectoryFiles(path p, vector<string> &files) {
    if (exists(p)) {
        if (is_regular_file(p)) {
            files.push_back(p.string());
            return;
        }
        else if (is_directory(p)) {
            for (directory_entry& x : directory_iterator(p)) {
                getDirectoryFiles(x.path(), files);
            }
        }
        else {
            cout << "exists, but not a file of a directory!\n";
            return;
        }
    }
    else {
        cout << "Path not exists!";
        return;
    }
};

來自Boost文檔的總體思路有所不同。 有人可以優化此代碼嗎?

為此有一個recursive_directory_iterator。

制作樣品:

fs::path dir = ".";
fs::recursive_directory_iterator it(dir), end;

std::vector<std::string> files;
for (auto& entry : boost::make_iterator_range(it, end))
    if (is_regular(entry))
        files.push_back(entry.path().native());

迭代目錄和文件operator ++引發異常時,Microsoft STL 2017中存在錯誤

recursive_directory_iterator::operator++: The system cannot find the path specified.

不要使用該錯誤的實現。 請改用boost。 我為此浪費了很多時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM