Design Requirements:
The format of the INI file is generally as follows:
[section1]
key1=value1
key2=value2
......
[section2]
key1=value1
key2=value2 #注释
......
The actual examples are:
#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
There are five elements: section name, key name, value value, comment #或者//start, flag character "["] "" = ". The corresponding relationship of the lookup item corresponds to Sectiong-key and value. Need to get is value. Class Inifile to implement two functions: Read the INI file, read the sect-key corresponding value. The following interface is implemented:
class IniFile{
public:
IniFile();
//打开ini文件
bool open(const char* pinipath);
//读取value值
const char* read(const char* psect, const char*pkey);
};
Design implementation:
Read the contents of the INI file by line with Ifstream
Identify the string of each line, parse out the sectiong,key,value, and comment.
Use Map<string, String, less<string> > to record all Sectiong-key and value.
Redefine class IniFile
typedef map<string, String, less<string> > Strmap;
typedef strmap::iterator Strmapit;
Const Char*const middlestring = "_____***_______";
Class IniFile
{
Public
IniFile () {};
~inifile () {};
BOOL Open (const char* pinipath)
{
Return Do_open (Pinipath);
}
String read (const char*psect, const Char*pkey)
{
string mapkey = Psect;
Mapkey + = middlestring;
Mapkey + = Pkey;
Strmapit it = C_inimap.find (Mapkey);
if (it = = C_inimap.end ())
Return "";
Else
Return it->second;
}
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 ();
}
Strmap C_inimap;
};