有没有办法读取C++中的文件文件夹?
Is there a way to read in a folder of files in C++?
我有一个包含近 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 平台上,有名为opendir
和readdir
的函数用于相同的目的。
如果要编写跨平台代码,有一些库可以在操作系统功能(如boost::filesystem
)之上提供抽象层。
- 如何将更多文件夹添加到c++include路径
- 从对象文件(.o)在macos上制作归档文件(.a文件)
- 有没有办法读取C++中的文件文件夹?
- 错误C1083:无法打开包含文件.文件正确包含在代码中
- NDK 无法看到头文件 .h 文件
- 文件文件夹关联或归属
- 如何以阻止的方式删除文件/文件夹
- 在MFC中序列化为Unicode文本文件-文件头错误
- (Qt C++)如何从QTableView将所选文件/文件夹打印到文本文件中
- 获取带有POCO的服务可执行文件文件夹
- 如何从文件文件夹创建自定义文件类型
- 如何在windows7有限内存的电脑上读取大文件?文件大小为25GB,但RAM容量只有16GB
- c++以二进制方式读取文件.文件结束的问题
- 如何在linux的makefile中使用头文件(.h)文件中定义的宏定义
- 如何从文件夹中读取文件?文件夹包含不同类型的文件名
- 如何查找指向文件/文件夹的所有硬链接和符号链接(Windows和UNIX)
- 生成临时文件/文件夹 c++ GTEST
- 更改应用程序文件(. c文件)的名称
- 使用vc++2010从usb读取文件/文件夹
- 为特定的文件/文件夹禁用-Wall标志