配置文件横行的开发任务,各种各样的配置文件着实令人心烦,却又无可奈何!
需求:
将配置文件中的某个Section枚举出来存入STL的MAP中,以便后续操作。
实现:
使用GetPrivateProfileSection获取Section下所有值,然后使用字符串处理之后存入MAP中。
函数原型如下(分为Unicode版和非Unicode版本):
GetPrivateProfileSection(
LPCSTR lpAppName, //Section名称
LPSTR lpReturnedString, //存放返回的字符串缓存
DWORD nSize, //缓存大小
LPCSTR lpFileName //配置文件路径
);
返回实际读取的字符数。
注意:GetPrivateProfileSection函数读去的Section以字符串的形式存入lpReturnedString中,键值对之间的空格会被过滤,换行符用‘\0'替换,结尾为'\0\0'.这里容易出问题。
假设配置文件property.ini内容如下:
[Section]
key1=value1
key2=value2
key3=value3
key4=value4
key5=value5
实现如下:
map<int,string>strMap;
void StrReplace(string src,string s)
{
string::size_type pos=0;
string::size_type start_pos = 0;
//根据字符串s分割字符串src
while((pos=src.find_first_of(s,pos))!=string::npos)
{
string temp = src.substr(start_pos,pos-start_pos);
string::size_type n_pos = 0;
//根据'='分割字符串src
while((n_pos=temp.find_first_of('=',n_pos)) != string::npos)
{
string key,value;
key = temp.substr(0,n_pos);
value = temp.substr(n_pos+1,temp.length());
n_pos++;
strMap.insert(make_pair<int,string>(atoi(key.c_str()),value));
}
start_pos = (++pos);
}
}
int ReadPaperTypeProperty()
{
char chSection[1024] = {0};
int nSize = GetPrivateProfileSection("Section",chSection,1024,"property.ini");
//替换字符串中间的'\0'
while (strlen(chSection) < nSize)
{
chSection[strlen(chSection)] = ',';
}
string strSection = chSection;
StrReplace(strSection,",");
return 0;
}
总结一下GetPrivateProfileSectionNames的用法:
GetPrivateProfileSectionNames的功能是枚举配置文件中所有Section的名称,函数原型如下:
GetPrivateProfileSectionNamesA(
LPSTR lpszReturnBuffer, //存放名称缓冲区
DWORD nSize, //缓冲区大小
LPCSTR lpFileName //配置文件名称
);
注意:读取的Section名同样以字符串的形式存入lpReturnedString中,键值对之间的空格会被过滤,换行符用‘\0'替换,结尾为'\0\0'.这里容易出问题。
int GetSectionNames()
{
char chSectionNames[1024] = {0};
int nSize = GetPrivateProfileSectionNames(chSectionNames,sizeof(chSectionNames),property.ini" );
//替换字符串中间的'\0'
while (strlen(chSectionNames) < nSize)
{
chSectionNames[strlen(chSectionNames)] = ',';
}
MessageBox(NULL,chSectionNames,"",MB_OK);
return nSize;
}