【问题标题】:Is there a way to read in a folder of files in C++?有没有办法读取 C++ 中的文件文件夹?
【发布时间】:2018-06-10 21:23:57
【问题描述】:

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

1) fin 可以读取 .doc 文件,但是因为 .doc 文件不是纯文本,所以会在屏幕上打印废话。

2) 我不知道如何让程序自动读取多个文件名不相关的文件。

由于这两个问题,我手动浏览了每个 .doc 文件并将它们更改为 .txt 文件。另外,我称它们为 1.txt、2.txt、3.txt 等,这样我就可以在 C++ 中使用 for 循环来读取它们(我会将循环控制变量 i 转换为字符串 x in每次迭代,并读入“x.txt”)。

虽然这会起作用,但我只完成了 83 个文件,并且花了大约一个小时。有没有办法让 C++ 自动读取所有这些文件? C++ 还必须先将每个文件都更改为 .txt 文件,这样我才能在屏幕上打印有意义的文本。

【问题讨论】:

    标签: c++ file input file-io inputstream


    【解决方案1】:

    Boost 库对于这些类型的文件/文件系统操作非常丰富。请检查下面的代码。这基本上会转到保存所有 doc 文件的文件夹 (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
    

    【讨论】:

      【解决方案2】:

      鉴于您在谈论 Microsoft Word 和“文件夹”,我猜您正在运行 Windows。

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

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

      如果你想编写跨平台代码,有一些库在操作系统函数之上提供抽象层,例如boost::filesystem

      【讨论】:

        猜你喜欢
        • 2021-08-02
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-02
        • 2022-08-04
        • 1970-01-01
        相关资源
        最近更新 更多