配置文件类似下面的格式
param1=value1
param2=value2
....
简单封装了c++类,可以读取任一参数
接口定义
/*
author cwliu
date: 2015-01-05
*/
#ifndef CONFIGFILE_H
#define CONFIGFILE_H
#include <string>
#include <string.h>
#include <stdio.h>
#include <map>
using namespace std;
typedef map<string,string> PARAM_MAP;
typedef map<string,string>::iterator paramIterator;
class CConfigFile
{
public:
static CConfigFile* GetInstanse()
{
if (!m_pInstanse)
{
m_pInstanse=new CConfigFile();
}
return m_pInstanse;
}
int LoadConfig(char* sFilePath);
int ReadParam(char* sParam,char* sValue);
private:
CConfigFile();
static CConfigFile* m_pInstanse;
char m_sConfigFilePath[128];
PARAM_MAP m_paramMap;
};
#endif /* CONFIGFILE_H */
实现
#include "ConfigFile.h"
CConfigFile* CConfigFile::m_pInstanse=NULL;
CConfigFile::CConfigFile()
{
memset(m_sConfigFilePath,0,128);
}
int CConfigFile::LoadConfig(char* sFilePath)
{
if (!sFilePath)
{
return -1;
}
FILE* pFile=fopen(sFilePath,"r");
if (!pFile)
{
return -1;
}
char sReadBuf[1024];
char* recv_ptr=NULL;
while (1)
{
memset(sReadBuf, 0, 1024);
recv_ptr = fgets(sReadBuf, 1024, pFile);
if (!recv_ptr)
{
return 0;
}
string line=recv_ptr;
int n=line.find('=');
if (n<0)
{
continue;
}
string param_name=line.substr(0,n);
string param_value=line.substr(n+1,line.length());
if (param_name.length()<=0)
{
continue;
}
m_paramMap.insert(make_pair(param_name,param_value));
}
return 0;
}
int CConfigFile::ReadParam(char* sParam,char* sValue)
{
string param_name=sParam;
paramIterator itor=m_paramMap.find(param_name);
if (itor!=m_paramMap.end())
{
string param_value=itor->second;
memcpy(sValue,param_value.c_str(),param_value.length());
printf("read param %s=%s\n",sParam,sValue);
return 0;
}
return -1;
}