test.ini文件如下:
[section1]
key1=value1
key2=value2
[section2]
key1=value1
key2=value2 #注释
用法如下:
CIniFile ini;
if(!ini.open("test.ini"))
return;
string strvalue = ini.read("section1", "key1");
if(strvalue.empty())
std::cout<<"can't find [section1] key1"<<endl;
else
std::cout<<"value="<<strvalue<<endl;
输出的为:value=value1
源代码如下:
(以下源码来至于http://www.stlchina.org/ 本人只做了一些小小的改动)
#if !defined(_INI_FILE__INCLUDED_)
#define _INI_FILE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#pragma warning(disable:4786)
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
typedef map<string, string, less<string> > MAP_STRING;
typedef MAP_STRING::iterator IT_MAP_STRING;
const char*const MIDDLESTRING = "_____***_______";
struct analyzeini
{
analyzeini(MAP_STRING & strmap):pmap(&strmap){}
void operator()( const string & strini)
{
int first =strini.find('[');
int last = strini.rfind(']');
if( first != string::npos && last != string::npos && first != last+1)
{
strsect = strini.substr(first+1,last-first-1);
return ;
}
if(strsect.empty())
return ;
if((first=strini.find('='))== string::npos)
return ;
string strtmp1= strini.substr(0,first);
string strtmp2=strini.substr(first+1, string::npos);
first= strtmp1.find_first_not_of(" \t");
last = strtmp1.find_last_not_of(" \t");
if(first == string::npos || last == string::npos)
return ;
string strkey = strtmp1.substr(first, last-first+1);
first = strtmp2.find_first_not_of(" \t");
if(((last = strtmp2.find("\t#", first )) != string::npos) ||
((last = strtmp2.find(" #", first )) != string::npos) ||
((last = strtmp2.find("\t//", first )) != string::npos)||
((last = strtmp2.find(" //", first )) != string::npos))
{
strtmp2 = strtmp2.substr(0, last-first);
}
last = strtmp2.find_last_not_of(" \t");
if(first == string::npos || last == string::npos)
return ;
string value = strtmp2.substr(first, last-first+1);
string mapkey = strsect + MIDDLESTRING;
mapkey += strkey;
(*pmap)[mapkey]=value;
return ;
}
private:
string strsect;
MAP_STRING *pmap;
};
class CIniFile
{
public:
CIniFile( ){};
~CIniFile( ){};
bool open(const char* pinipath)
{
if (!IsValid(pinipath))
{
return false;
}
return do_open(pinipath);
}
string read(const char*psect, const char*pkey)
{
if (!IsValid(psect) || !IsValid(pkey))
{
return string();
}
string mapkey = psect;
mapkey += MIDDLESTRING;
mapkey += pkey;
IT_MAP_STRING it = c_inimap.find(mapkey);
if(it == c_inimap.end())
return string();
else
return it->second;
}
static bool IsValid(const char* psz)
{
return !(psz == NULL && strlen(psz)==0);
}
protected:
bool do_open(const char* pinipath)
{
ifstream fin(pinipath);
if(!fin.is_open())
return false;
vector<string> strvect;
while(!fin.eof())
{
string inbuf;
getline(fin, inbuf,'\n');
strvect.push_back(inbuf);
}
if(strvect.empty())
return false;
for_each(strvect.begin(), strvect.end(), analyzeini(c_inimap));
return !c_inimap.empty();
}
MAP_STRING c_inimap;
};
#endif // !defined(_INI_FILE__INCLUDED_)