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

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

本文关键字:文件 文件夹 C++ 读取 有没有      更新时间:2023-10-16

我有一个包含近 200 个 word 文档的文件夹,我想使用图书馆 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文件,以便我可以在屏幕上打印有意义的文本。

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

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

Windows API 提供FirstFirstFile/FindNextFile对函数,允许程序自动查找现有文件的名称。 官方示例名为"列出目录中的文件">

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

如果要编写跨平台代码,有一些库可以在操作系统功能(如boost::filesystem)之上提供抽象层。