获取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;
}

结果
执行效果

在C/C++编程中,判断INI文件中某个键值对是否全部读取完毕可以通过以下步骤: 1. 打开INI文件:使用 fopen 函数打开INI文件获取文件指针。 2. 定位到指定:通过读取每一行的内容,并判断该行是否是目标的开始行(以'['开头)来定位到指定。 3. 读取键值对:在定位到目标后,可以通过 fgets 函数逐行读取的内容,判断读取的内容是否是键值对(包含'='字符),如果是,则进行处理。 4. 判断是否读取完毕:判断条件可以有多种方式,例如可以在循环过程中使用计数器记录读取键值对数量,然后与目标中的键值对总数进行对比,如果相等则表示读取完毕。 5. 关闭INI文件:使用 fclose 函数关闭打开的INI文件。 以下是一个简单的示例代码: ```c #include <stdio.h> #include <string.h> int main() { FILE *file; char line[256]; int count = 0; int targetCount = 0; int isInTargetSection = 0; // 打开INI文件 file = fopen("config.ini", "r"); if (file == NULL) { printf("无法打开INI文件\n"); return -1; } // 定位到指定 while (fgets(line, sizeof(line), file) != NULL) { if (line[0] == '[' && strstr(line, "[TargetSection]") != NULL) { isInTargetSection = 1; } if (isInTargetSection && strchr(line, '=') != NULL) { targetCount++; } // 判断是否读取完毕 if (targetCount > 0 && count == targetCount) { break; // 读取完毕 } } // 关闭INI文件 fclose(file); // 输出结果 printf("目标中的键值对总数:%d\n", targetCount); printf("已读取键值对数量:%d\n", count); return 0; } ``` 注意:示例代码仅用于演示思路,请根据具体的需求和INI文件格式进行相应的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值