gpt4 book ai didi

c++ - 使用 Boost 遍历目录失败

转载 作者:行者123 更新时间:2023-11-28 08:08:24 25 4
gpt4 key购买 nike

我在使用以下函数时遇到了一些问题。它应该被赋予一个路径和一组允许的文件扩展名,然后找到该路径中具有任何这些扩展名的所有文件。相反,它什么也没找到并返回一个空集。

std::set<boostfs::path> scan_directory(const boostfs::path& p,
const bool recurse,
const std::set<std::string>& allowed) {
std::string ext ;
std::set<boostfs::path> incs, incs2 ;
boostfs::path::iterator itr ;

// Extract directory and filename
boostfs::path file = p.filename() ;
boostfs::path dir = p.parent_path() ;

std::cout << "path: " << p.string() << std::endl ;

for (itr = dir.begin(); itr != dir.end(); ++itr) {
if (boostfs::is_directory(*itr)) {
if (recurse) {
std::cout << "dir: " << itr->string() << std::endl ;
incs2 = scan_directory(*itr, true, allowed) ;
incs.insert(incs2.begin(), incs2.end()) ;
}
} else {
// Don't include the original source
if (*itr != p) {
// Include only allowed file types
ext = itr->extension().string() ;
std::cout << "file: " << itr->string() << std::endl ;
std::cout << "ext: " << ext << std::endl ;
if (allowed.find(ext) != allowed.end()) {
incs.insert(*itr) ;
}
}
}
}

return incs ;
}

输出到 cout 只是为了调试。我正在使用以下目录结构对其进行测试:

./test/cpp/
foo.cpp
foo.h
test.cpp
./test/cpp/bar/
baz.cpp
baz.h

我使用路径“test/cpp/test.cpp”调用函数,recurse true 和包含一个字符串“.cpp”的集合。我从打印品中得到以下输出,

path: test/cpp/test.cpp
dir: test
path: test
file: cpp
ext:

然后函数结束,程序的其余部分继续,只是给它一组空文件,所以没有太多工作要做。给定测试目录,它应该返回一个包含“test/cpp/foo.cpp”和“test/cpp/bar/baz.cpp”的集合。

我相当确定它不久前工作正常,但我不确定它是什么时候坏的,或者我做了什么让它坏了。我敢肯定这是一些小的、烦人的技术问题。

最佳答案

我发现了我的问题。我使用的是 path::iterator 而不是 directory_iterator(或 recursive_directory_iterator)所以我循环遍历路径的组件而不是路径的内容目录。我本可以发誓它早点奏效,但这可能只是运气。

这是我的工作代码

std::set<boostfs::path> scan_directory(const boostfs::path& p,
const bool recurse,
const std::set<std::string>& allowed) {
std::string ext ;
std::set<boostfs::path> incs ;

// Extract directory and filename
boostfs::path file = p.filename() ;
boostfs::path dir = p.parent_path() ;

boostfs::recursive_directory_iterator itr(dir), itr_end ;

while(itr != itr_end) {
if (boostfs::is_directory(*itr)) {
itr.no_push(!recurse) ;
} else {
// Don't include the original source
if (*itr != p) {
// Include only allowed file types
ext = itr->path().extension().string() ;
if (allowed.find(ext) != allowed.end()) {
incs.insert(*itr) ;
}
}
}

itr++ ;
}

return incs ;
}

我会让大家知道 Boost 文档中遍历目录的示例非常糟糕

关于c++ - 使用 Boost 遍历目录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719039/

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