如何从 C++17 以外的目录中读取 txt 文件(未知名称)?

How to read the txt files (unknown names) from a directory but C++17?

我试图用 header <experimental/filesystem> 做到这一点,但在 c++17 中它被弃用了。我没有把代码放在这里,因为我什至不确定我在做什么。

基本上,我想查看与可执行文件位于同一目录中的所有 txt 文件,但我们不知道这些 txt 文件的名称或有多少 txt 文件。当然,能够阅读它们。

使用 C++ 17 这真的很容易。

试试下面的程序:

#include <iostream>
#include <filesystem>
#include <vector>
#include <iterator>
#include <algorithm>

namespace fs = std::filesystem;

int main(int argc, char* argv[]) {

    // The start path. Use Program path
    const fs::path startPath{ fs::path(argv[0]).parent_path() };

    // Here we will store all file names
    std::vector<fs::path> files{};

    // Get all path names
    std::copy_if(fs::directory_iterator(startPath), {}, std::back_inserter(files), [](const fs::directory_entry& de) { return de.path().extension() == ".txt"; });

    // Output all files
    for (const fs::path& p : files) std::cout << p.string() << '\n';

    return 0;
}

我们从 argv[0] 获取路径名,然后使用 directory_iterator 遍历所有文件。

然后,如果扩展名为“.txt”,我们会将路径名复制到生成的文件向量中。

我不确定,我应该进一步解释。有问题请追问