获取INI文件某个节下的所有键值

本文介绍了一个C++程序,用于读取config.ini配置文件中特定节下的所有键值对,并将其存储到map中。示例代码展示了如何使用GetPrivateProfileSection函数从.ini文件读取数据,然后通过AfxExtractSubString提取键和值,最终存储到map中进行遍历和打印。
摘要由CSDN通过智能技术生成

config.ini文件内容

[name]
zhangsan = 19
lisi = 20
wangwu = 18

读取代码

#include <afxwin.h>
#include <tchar.h>
#include <iostream>
#include <map>
using namespace std;

map<CString, CString> mapIniKeyValue;

/*
功能:获取ini文件某个节下的所有键值。
参数:
pIniFilePath:ini文件路径;
pSectionName:需要读取的节名;
mapIniKeyValue:map类型,用于保存pSectionName节名下的所有键值
返回值:无
*/
VOID GetAllKeyValueOfIniFileOneSection(TCHAR *pIniFilePath, TCHAR *pSectionName, map<CString, CString>&mapIniKeyValue)
{	
	TCHAR szBuf[4096] = { 0 };
	DWORD readlen = ::GetPrivateProfileSection(pSectionName, szBuf, 4096, pIniFilePath);
	TCHAR *pbuf = szBuf;
	size_t size = _tcslen(pbuf);
	
	//如果读取到的行,长度不为0时,说明此行存在,继续取值
	while (size) 
	{
		CString str = pbuf;
		CString strKey, strValue;
		if (AfxExtractSubString(strKey, (LPCTSTR)str, 0, _T('=')) && AfxExtractSubString(strValue, (LPCTSTR)str, 1, _T('=')))
		{
			if (!mapIniKeyValue.count(strKey))
			{
				mapIniKeyValue.insert(make_pair(strKey, strValue));
			}			
		}
		pbuf += size + 1;
		size = _tcslen(pbuf);
	}
	return;
}

int _tmain()
{
	GetAllKeyValueOfIniFileOneSection(_T(".\\config.ini"), _T("name"), mapIniKeyValue);
	map<CString, CString>::iterator it;
	it = mapIniKeyValue.begin();

	while (it != mapIniKeyValue.end()) {
		
		wcout << (it->first).GetString() << L'=' << it->second.GetBuffer() << endl;
		it++;
	}
	system("pause");
	return 0;
}

结果
执行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值