c++ - 将目录迭代器切换为同一循环的递归?

标签 c++ filesystems

是否可以在同一个循环中在目录迭代器的递归和非递归版本之间切换?我想这样做的原因是我真的不想仅仅为了递归版本而重复我的整个代码。

#include <iostream>
#include <filesystem>
#include <string>

int main()
{
    std::string DirPath = "C:\\Users";

    // Switch loop to recusive
    bool isRecursive = false;

    // ERROR: Not working
    auto it = isRecursive ? std::filesystem::recursive_directory_iterator(DirPath) : 
       std::filesystem::directory_iterator(DirPath);

    for (const auto& entry : it) {

        if (std::filesystem::is_regular_file(entry)) {

            // .......
        }
    }

}

最佳答案

它不起作用,因为这两个迭代器具有不同的类型并且不能转换为通用类型。因此 auto 现在不能,它应该是什么类型。你有两种可能性:

recursive_directory_iterator 有方法 disable_recursion_pending ,这会在下一个增量之前禁用递归,因此您必须在每个循环中调用一次。

问题“我有两件非常相似的事情,它们的功能几乎相同,但并不完全相同,我不想重复编写我的代码。”非常适合应用模板。写一个方法

template<typename DirectoryIter>
void iter_dir(DirectoryIter it)
{ /* your code */ }

void iter_dir(const std::string& DirPath, bool recursive) // So you don't have to construct the iterators in your caller code
{
    if(recursive)
        iter_dir(std::filesystem::recursive_directory_iterator(DirPath));
    else
        iter_dir(std::filesystem::directory_iterator(DirPath));
} 

我个人更喜欢第二种变体。我发现它比在每次迭代中使用递归迭代器更简洁。

关于c++ - 将目录迭代器切换为同一循环的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59116888/

相关文章:

linux - 安装自定义文件系统模块

c++ - 与通配符匹配的文件名

windows - 为什么 Windows 将新创建文件的 "created time"属性设置为旧时间?

c++ - gcc 中自定义对象的 dlib 序列化失败

c++ - doxygen:pdf 中损坏的目录

c++ - 堆栈上的匿名对象,在 C++ 中?

javascript - 有没有办法在 PWA 中缓存多个文件?

c++ - deleted 指针指向什么?

c++ - OpenSL ES 中是否有等效于 OpenAL <alc.h> 的内容?

python - 在 `pyarrow` 测试中使用内存文件系统