需求:
在gavin的D:\wamp\www\OM\products目录下有600多个htm文件,现需要把所有文件中的<title>.....</title>提取到一个文本文件中。文本文件分两列,第一列是文件的绝对路径,第二列是该文件对应的<title>.....</title>,两列之间用分号隔开。
已知:D:\wamp\www\OM\products下有一个fileList.txt存放着当前文件夹下的所有文件。
解决:用C++写一个函数,从fileList.txt中一次读取一个文件名,打开文件,提取<title>.....</title>,将文件的绝对路径和<title>.....</title>写到D:\wamp\www\OM\products\mapfile.txt中。
源代码如下:
// extraDocElem.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <assert.h>
using namespace std;
//在某文件中查找字符,并返回字符串所在行的内容
string getStrfromFile(string &filename,string &str)
{
string strline;
ifstream fin(filename.c_str());
if (!fin){
cout<<"Error opening the file " <<filename<<"for input"<<endl;
exit(-1);
}
string::size_type err;
while(getline(fin,strline))
{
//cout<<strline.c_str()<<endl;
err=strline.find(str);
if(err==string::npos)
{
//cout<<"no title in this file"<<endl;
}
else
{
//cout<<strline.c_str()<<endl;
//cout<<err<<endl;
break;
}
}
fin.close();
return strline;
}
int _tmain(int argc, _TCHAR* argv[])
{
string fileList= "D:\\wamp\\www\OM\\products\\fileList.txt"; //存储文件路径的文件
string mapfilename = "D:\\wamp\\www\OM\\products\\mapfile.txt";//存储映射的文件
string strdir;//文件的绝对路径
string strpath="D:\\wamp\\www\\OM\\products\\";
string strfind="<title>";
string strtitle;
//1.每次读取一行到一个字符串
ifstream fin(fileList.c_str());
if (!fin){
cout<<"Error opening the file " <<fileList<<"for input"<<endl;
exit(-1);
}
ofstream out_file(mapfilename.c_str(),ios::app);
while(getline(fin,strdir))
{
strdir=strpath+strdir;
strtitle=getStrfromFile(strdir,strfind);
cout<<strdir.c_str()<<endl;
out_file<<strdir;
out_file<<";";
out_file<<strtitle;
out_file<<"\n";
}
out_file.close();
fin.close();
return 0;
}