有没有办法读取 C++ 中的文件文件夹?

Is there a way to read in a folder of files in C++?

我有一个包含近 200 个单词文档的文件夹,我想使用库 fstream 中的 ifstream fin 将它们读入 C++。我有两个问题:

1) fin 能够读入.doc 文件,但由于.doc 文件不是纯文本,所以屏幕上会打印出无意义的内容。

2) 我不知道有什么办法可以让程序自动读入多个文件名不相关的文件。

由于这两个问题,我手动检查每个 .doc 文件并将它们更改为 .txt 文件。此外,我将它们称为 1.txt、2.txt、3.txt 等,以便我可以在 C++ 中使用 for 循环来读取它们(我将转换循环控制变量i 在每次迭代中写入字符串 x,并读入 "x.txt").

虽然这会奏效,但我只完成了 83 个文件,大约花了一个小时。有没有办法让 C++ 自动读取所有这些文件? C++ 也必须首先将每个更改为 .txt 文件,以便我可以在屏幕上打印有意义的文本。

鉴于您在谈论 Microsoft Word 和 "folder",我猜您是 运行 Windows。

Windows API 提供了 FirstFirstFile / FindNextFile 对函数,它们允许您的程序自动查找现有文件的名称。 The official example is named "Listing the Files in a Directory"

在 Linux 和 Unix 平台上,有名为 opendirreaddir 的函数,它们的用途相同。

如果您想编写跨平台代码,有些库会在 OS 函数之上提供抽象层,例如 boost::filesystem.

Boost 库对于这些类型的文件/文件系统操作非常丰富。请检查下面的代码。这基本上会转到您保存所有文档文件的文件夹 (ws),并遍历其中的所有文件。该代码假定文件夹 'ws' 有 只有 个文件,没有文件夹。一旦你有了文件名,你就可以对其进行各种操作。

我不明白您为什么要将扩展名更改为 txt,但包含了执行此操作的几行。更改扩展名不会影响其内容。

#include <sstream>
#include <iostream>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main(){

    // ref : https://theboostcpplibraries.com/boost.filesystem-paths

    // ws : workspace where you keep all the files
    fs::path ws = fs::path(getenv("HOME")) / "ws";

    // ref : https://theboostcpplibraries.com/boost.filesystem-iterators
    fs::directory_iterator it{ws};

    while (it != fs::directory_iterator{}){
        std::cout << "Processing file < " << *it << " >" << std::endl;
        // ... do other stuff

        // Parse the current filename into its parts, then change the extension to txt
        // ref : https://theboostcpplibraries.com/boost.filesystem-paths
        std::stringstream ss;
        ss << (ws / fs::path(*it).stem()).native() << ".txt";

        fs::path new_path(ss.str());

        std::cout << "Copying into < " << new_path << " >" << std::endl;

        // ref : http://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/reference.html
        fs::copy_file(*it++, new_path, fs::copy_option::overwrite_if_exists);
    }

    return 0;
}

你可以用这个编译:

g++ -std=c++14 -o main main.cc -lboost_filesystem -lboost_system