//readCfg.h 头文件
/********************************************************************
created: 2009/03/09
created: 3:9:2009 9:30
file base: readCfg
file ext: h
author: 2009-3-9
purpose:
*********************************************************************/
#ifndef READCFG_H_
#define READCFG_H_
#include <vector>
#include <map>
#include <string>
#include <string.h>
#include <iostream>
using namespace std;
class readCfg
{
public:
readCfg();
~readCfg();
void load(char* filename);
void skipSpace(char* temp1,string& temp2);
void getKeyAndValue(char* src,string& key,string& value);
char* getProperty(char* key)
{
if(0==m_KeyToValue.count(key))
return NULL;
return (char*)m_KeyToValue[key].c_str();
}
void print();
protected:
private:
string m_filename;
FILE* m_pfile;
map<string,string> m_KeyToValue;
};
#endif
readCfg.cpp cpp文件
//#include "stdafx.h"
#include "readCfg.h"
/**********************************************************/
/*去除字符串开始的空格符和tab键,并且去除
字符串末尾的空格、tab键和回车换行符*/
/***********************************************************/
void readCfg::skipSpace(char* temp1,string& temp2)
{
//如果是空字符串则直接返回
if('/0' == temp1[0]||'/n' == temp1[0])
{
temp2="";
return;
}
int mlen = strlen(temp1);
int begin = 0;
//int end = 0;
for (int i = 0 ;i<mlen;i++)
{
//如果是空格或者tab键则删除
if (*(temp1+i) == ' '||*(temp1+i) =='/t')
{
begin = i+1;
}
else
{
break;
}
}
if ('#' == temp1[0])
{
temp2="";;
return;
}
for (int j = mlen-1;j>=0;j--)
{
if (*(temp1+j) == ' '||*(temp1+j) =='/t'||'/n' == *(temp1+j) ||'/r' == *(temp1+j))
{
*(temp1+j)='/0';
}
else
{
break;
}
}
temp2 = temp1+begin;
}
void readCfg::getKeyAndValue(char* src,string& key,string& value)
{
if ('/0' == *src)
{
key="";
value="";
return;
}
string text(src);
string::size_type pos = text.find("=");
if (pos == string::npos)
{
key="";
value="";
return;
}
key = text.substr(0,pos);
value = text.substr(pos+1);
skipSpace((char*)key.c_str(),key);
skipSpace((char*)value.c_str(),value);
}
readCfg::readCfg()
{
}
readCfg::~readCfg()
{
fclose(m_pfile);
}
void readCfg::load(char* filename)
{
char line[100]="";
string text="";
vector<string> textvec;
m_filename = filename;
m_pfile = fopen(m_filename.c_str(),"r");
if (NULL == m_pfile)
{
m_pfile = fopen(m_filename.c_str(),"r");
}
int i =0;
while ( NULL != fgets( line, 100, m_pfile ) )
{
skipSpace(line,text);
if (text.empty())
{
continue;
}
textvec.push_back(text);
i++;
}
int size = textvec.size();
string key;
string value;
for (int i = 0; i < size; i++)
{
getKeyAndValue((char*)textvec[i].c_str(),key,value);
if (key.empty())
{
continue;
}
m_KeyToValue[key] = value;
}
}
void readCfg::print()
{
map<string,string>::iterator iter = m_KeyToValue.begin();
for (;iter!=m_KeyToValue.end();iter++)
{
cout<<iter->first<<" = "<<iter->second<<endl;
}
}