c++ - 如何使用文件系统列出目录中具有给定扩展名的所有文件?

标签 c++ visual-studio-2015

<分区>

由于 filesystem 存在于编译器的实验部分,并且将出现在最新版本的 C++ 中,如何使用它从目录中列出与给定扩展名匹配的文件?

最佳答案

您可以使用 std::experimental::filesystem::directory_iterator并手动过滤:

for(const auto& p : fs::directory_iterator("some_directory"))
{
    if(p.path().extension() == ".txt")
    { 
        /* ... */
    }
}

您可以创建一个漂亮的包装器,如下所示:

template <typename TF>
void for_files_with_extension(std::string_view dir, std::string_view ext, TF&& f)
{
    for(const auto& p : fs::directory_iterator(dir))
    {
        if(p.path().extension() == ext)
        { 
            f(p);
        }
    }
}

可以这样使用:

for_files_with_extension("/home/someone/", ".txt", 
    [](const auto& p){ std::cout << "Found text file at " << p << "\n"; });

关于c++ - 如何使用文件系统列出目录中具有给定扩展名的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633529/

相关文章:

c++ - 使用 QDataStream 序列化自定义类导致 C2679 错误

c++ - 这个工作线程怎么会被阻塞却显示正在运行呢?

c++ - std::vector 保证不在元素之间留下空隙吗?

c - 我无法更改 c、Visual Studio 中的当前路径

git - Visual Studio 中的本地 Git 存储库 url 错误 : Unsupported URL protocol

c# - Visual Studio Code Coverage 在 vNext 项目中过时了吗?

c++ - 默认构造函数为空时做什么?

c++ - 基于模板类型指针性的条件函数行为

tfs - vs2015不断添加project.lock.json到tfs

visual-studio - 带有 TFS2015 和 VisualStudio2015 的 xUnit 没有找到任何测试