【问题标题】:How to read the txt files (unknown names) from a directory but C++17?如何从 C++17 以外的目录中读取 txt 文件(未知名称)?
【发布时间】:2021-01-05 03:40:53
【问题描述】:

我试图使用标题 <experimental/filesystem> 来执行此操作,但在 c++17 中它已被弃用。我没有把代码放在这里,因为我什至不确定我在做什么。

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

【问题讨论】:

  • 我认为 在 c++17 中已成为标准,因此不再是实验性的。试试#include <filesystem>
  • 从 C++17 开始,改用 <filesystem> 标头。
  • 您可能会发现A: experimental::filesystem linker error 提供了丰富的信息,尤其是更新(即使该问题与此问题并不真正重复)。

标签: c++ c++17 txt


【解决方案1】:

使用 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”,我们会将路径名复制到生成的文件向量中。

我不确定,我应该进一步解释什么。如有问题,请提出。

【讨论】:

  • 非常好的一个,如果我想查看其他(无txt)文件,这种方式很容易获取所有文件。
猜你喜欢
  • 2016-11-02
  • 2015-07-03
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多