使用Boost遍历目录失败

Traversing directory with Boost fails

本文关键字:失败 遍历 Boost 使用      更新时间:2023-10-16

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

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