我有一个包含近 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 文件,以便我可以在屏幕上打印有意义的文本。
最佳答案
对于这些类型的文件/文件系统操作,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
关于c++ - 有没有办法读取 C++ 中的文件文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039496/