给一个配置文件:比如http服务器发来的header信息
HTTP/1.1 200 OK
Date: Sat, 21 Jan 2012 04:49:14 GMT
Server: Apache/2.2.20 (Ubuntu)
Last-Modified: Sat, 03 Sep 2011 11:05:41 GMT
ETag: "28f96cd-4b500a-4ac07756b656f"
Accept-Ranges: bytes
Content-Length: 4935690
Content-Type: audio/mpeg
要分析出来生成一个个条目:
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <algorithm>
#include <mem.h>
#include <boost/lambda/lambda.hpp>
#include <boost/bind/bind.hpp>
using namespace std;
//给出文件路径,变量与值的分割符,将其转换成map结构
map<string, string> analyseConfig(string configFile, char sliceChar)
{
map<string, string> configMap;
ifstream is;
is.open(configFile.c_str(), ios::binary);
char* buffer = new char [100] ;
string variable;
string value;
int count;
int state = 1;
while (1)
{
memset(buffer,-1,100);
is.read(buffer, 100);
for (count = 0; count != 100; count++)
{
if (buffer[count] == -1)
{
if (state == 1)
{
return configMap;
}
else
{
configMap[variable] = value;
}
return configMap;
}
switch (buffer[count])
{
case '\n':
if(!variable.empty() && !value.empty())
{
configMap[variable] = value;
}
variable.clear();
value.clear();
state = 1;
continue;
break;
case ' ':
continue;
break;
default:
break;
}
if (buffer[count] != sliceChar)
{
if (state == 1)
{
variable.push_back(buffer[count]); //if it is variable add the char to variable;
}
else
{
value.push_back(buffer[count]); //else add the char to value;
}
}
else
{
if(state == 2)
{
value.push_back(buffer[count]);
}
else
{
state = 2;
}
}
}
}
is.close();
return configMap;
}
void printString(string s,string r)
{
cout << s <<":"<< r<<endl;
}
int main()
{
ifstream is;
is.open("header.txt", ios::binary);
is.seekg(0, ios::end);
cout << "file length:" << is.tellg() << endl;
is.seekg(0, ios::beg);
map<string, string> config = analyseConfig("header.txt", ':');
cout <<"total items:"<< config.size()<<endl;
for_each(
config.begin(),
config.end(),
boost::bind(
&printString,
boost::bind(&map<string,string>::value_type::first,_1),
boost::bind(&map<string, string>::value_type::second, _1)
)
);
cout<<endl;
cout<<"for example:"<<endl;
cout<<"item:"<<"Content-Length"<<endl<<"values:"<<config["Content-Length"]<<endl;
return 0;
}