C++String应用:批量提取所有文件中的唯一元素

本文介绍了一个使用C++编写的程序,该程序能够从指定目录下的大量HTML文件中批量提取<title>标签内的文本内容,并将文件路径及<title>内容记录到一个文本文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:

在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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值