打开指定文件夹中的所有文本文件
Open all text files in given folder
我试图打开文件夹和子文件夹中的所有文本文件,我给程序作为参数并在其中搜索文本。现在如果我用。而不是路径,它像我想要的那样打开文件。但是,只要我给我的计算机中的任何其他文件夹作为参数(不是一个目标文件是),它将不会打开文件。我该怎么修理它?我有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());
这可能不是最规范或最有效的方法。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入