【发布时间】:2014-05-18 10:52:59
【问题描述】:
我试图打开一个文件夹和子文件夹中的所有文本文件,我作为参数提供给程序并在其中搜索文本。现在,如果我使用 .它不是路径,而是像我想要的那样打开文件。但是,一旦我将计算机中的任何其他文件夹作为参数(不是目标文件所在的文件夹),它就不会打开文件。我该如何解决?我有 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;
}
【问题讨论】:
-
“它不会打开文件”不是一个非常有用的问题描述,并且“一个文件夹”和“任何其他文件夹”不是对您的测试数据非常有用的描述, 任何一个。也许你可以详细说明?
-
"它不会打开文件" - 它不会进入循环 while(inFile){} - 一个文件夹,以及任何其他文件夹 - 一个文件夹是我给程序的路径,它可以是我电脑中的任意路径,其他文件夹是该文件夹的子文件夹
-
您应该检查
itr->path().filename()的值。因为如果文件的部分是some/directory/foo.txt,但.filename()只是返回foo.txt,您将无法打开它,因为路径丢失。当然,使用其他文件系统库很容易犯错误。 -
你是正确的 .filename() 只返回 foo.txt 没有路径。而且我相信这是我遇到的主要问题,但我怎样才能获得整个路径?