VC枚举配置文件的Section存入Map

本文介绍了如何在VC++中使用GetPrivateProfileSection函数将配置文件的Section枚举并存储到STL的MAP中。通过示例详细讲解了函数的使用方法,包括处理字符串和换行符的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文件横行的开发任务,各种各样的配置文件着实令人心烦,却又无可奈何!

需求:

将配置文件中的某个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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值