我试图打开我给程序提供的文件夹和子文件夹中的所有文本文件作为参数并在其中搜索文本。现在,如果我使用。而不是路径,它会像我想要的那样打开文件。但是,只要将计算机中的任何其他文件夹作为参数(而不是目标文件所在的文件夹)作为参数,它就不会打开文件。我该如何解决?我有Windows,并且正在使用MinGw作为编译器。
#include <iostream>
#include <cstdlib>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include <iterator>
#include <fstream>
namespace po = boost::program_options;
using namespace std;
using namespace boost;
using namespace boost::filesystem;
int main (int argc, char* argv[]) {
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("folder", po::value<std::string>(), "find files in this folder")
("text", po::value<std::string>(), "text that will be searched for");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
filesystem::path current_dir (vm["folder"].as<string>());
filesystem:: recursive_directory_iterator end_itr;//recursive lisatud
for ( filesystem::recursive_directory_iterator itr( current_dir );
itr != end_itr;
++itr )
{
//cout << itr->path ().filename () << endl;
if(itr->path().filename().extension()==".txt"||itr->path().filename().extension()==".docx"||itr->path().filename().extension()==".doc"){
ifstream inFile(itr->path().filename().string());
//ifstream inFile("c:\\somefile.txt"); //this would open file
cout<<itr->path().filename().string()<<endl; //this prints out all the file names without path, like somefile2.txt for example
while ( inFile )
{
std::string s;
std::getline( inFile, s );
if (inFile){
std::cout << s << "\n";
if(s.find(vm["text"].as<string>())!= string::npos){
cout<<"found it"<<endl;
}
}
}
}
}
return EXIT_SUCCESS;
}
这是问题所在:
ifstream inFile(itr->path().filename().string())
或者更具体地说,itr->path().filename()
仅返回名称的文件,而不是完整的路径到该文件。如果该文件不在程序的当前工作目录中,则打开时将遇到问题:找不到该名称的文件,或者找到具有相同名称的本地文件,该文件将不是该文件你真的想要!
在执行递归目录迭代时,当前工作目录不会更改。
itr->path()
返回boost::filesystem::path
取消引用时的实例...该类的文档可在此处找到。我相信你想做的是
ifstream inFile(itr->path().c_str());
但是,这可能不是规范或最有效的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句