用STL快速編寫ini配置檔案識別類

2021-05-08 09:18:59 字數 2613 閱讀 5091

inifileanalyse.h檔案:

#include

#include

#include

#include

#include

#include

using namespace std;

typedef map> strmap;

typedef strmap::iterator strmapit;

const char * const middlestring = "____***____";

struct analyzeini

;void operator() (const string & strini)

if (strsect.empty())

if ((first = strini.find('=')) == string::npos)

// 獲取「=」左右兩邊的字串

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))

// 得到key

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) )

last = strtmp2.find_last_not_of(" /t");

if ((first == string::npos) || (last == string::npos))

string keyvalue = strtmp2.substr(first, last - first + 1);

string mapkey = strsect + middlestring;

mapkey += strkey;

(*pmap)[mapkey] = keyvalue;

return;}};

class inifile

;~inifile() {};

bool open(const char *pinipath)

string read(const char *psect, const char *pkey)

else

}void print()

for (strmapit it = c_inimap.begin(); it != c_inimap.end(); it++)

}protected:

bool do_open(const char *pinipath)

vectorstrvect;

while (!fin.eof())

if (strvect.empty())

for_each(strvect.begin(), strvect.end(), analyzeini(c_inimap));

return !c_inimap.empty();

}private:

strmap c_inimap;

};使用:

#include "stdafx.h"

#include

#include

#include "inifileanalyse.h"

using namespace std;

int _tmain(int argc, _tchar* argv)

string strvalue = ini.read("exe", "passwd");

if (strvalue.empty())

else

ini.print();

return 0;

}test.ini檔案內容:

#ini for path

[path]

dictfile = /home/tmp/dict.dat

inputfile= /home/tmp/input.txt

outputfile= /home/tmp/output.txt

#ini for exe

[exe]

user= winter       //user name

passwd= 1234567    #pass word

database= mydatabase

用STL快速編寫ini配置檔案識別類

winter ini檔案是技術人員經常用到的一種系統配置方法,如何讀取和快速識別ini檔案中的內容實現起來比較繁瑣。stl強大的功能在於能快速的實現排序 查詢 識別等功能。本文通過stl中的map,string,vector,ifstream等,來快速實現ini檔案的識別類class inifile...

用STL快速編寫ini配置檔案識別類

設計需求 ini檔案的格式一般如下 section1 key1 value1 key2 value2 section2 key1 value1 key2 value2 注釋 實際的例子是 ini for path path dictfile home tmp dict.dat inputfile h...

用C 讀寫ini配置檔案

ini就是擴充套件名為 ini 的檔案,其實他本身是個文字檔案,可以用記事本打工,主要存放的是使用者所做的選擇或系統的各種引數.ini檔案其實並不是普通的文字檔案.它有自己的結構.由若干段落 section 組成,在每個帶括號的標題下面,是若干個以單個單詞開頭的關鍵字 keyword 和乙個等號,等...