gpt4 book ai didi

c++ - 一种使用boost和c++列出目录和子目录下所有文件的方法

转载 作者:行者123 更新时间:2023-11-30 03:41:01 27 4
gpt4 key购买 nike

我有以下代码来搜索目录及其所有子目录中的所有文件。该代码对嵌套子目录使用递归。

#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 documentation有一个转折。任何人来优化这段代码?

最佳答案

为此有一个 recursive_directory_iterator。

制作 sample :

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());

关于c++ - 一种使用boost和c++列出目录和子目录下所有文件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com