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;
}
结果