使用Boost遍历目录失败
Traversing directory with Boost fails
我在使用以下函数时遇到了一些问题。应该给它一个路径和一组允许的文件扩展名,然后在该路径中找到所有具有这些扩展名的文件。相反,它一无所获,并返回一个空集。
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"调用函数,递归true和一个包含一个字符串".cpp"的集合
path: test/cpp/test.cpp
dir: test
path: test
file: cpp
ext:
然后函数结束,程序的其余部分继续,只给了它一个空的文件集,所以没有太多的工作要做。给定测试目录,它应该返回一个包含"test/cpp/foo.cpp"answers"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文档中迭代目录的例子是AWFUL
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何正确地推回然后遍历堆中对象的向量?
- 遍历二维数组的所有子数组
- 如何在可变参数模板函数中遍历可变参数元组?
- 避免在遍历 IShellItemArray 时出现代码重复
- 从特定键开始遍历地图
- 关于链表遍历和调试的困惑
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 使用Boost遍历目录失败