我有一个包含近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库对于这些类型的文件/文件系统操作非常丰富。请检查下面的代码。基本上,这将转到您保留所有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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句