当前位置: 首页 > article >正文

C++ ini配置文件的简单读取使用

ini文件就是简单的section 下面有对应的键值对
在这里插入图片描述

std::map<std::string, std::map<std::string, std::string>>MyIni::readIniFile() {

	std::ifstream file(filename);

	if (!file.is_open()) {
		std::cerr << "Error: Unable to open file " << filename << std::endl;
		return iniData;
	}

	std::string line;
	std::string currentSection;

	while (std::getline(file, line)) {
		// 移除行首和行尾的空格和制表符
		line.erase(line.find_last_not_of(" \t") + 1);
		line.erase(0, line.find_first_not_of(" \t"));

		//cout << "line:" << line << endl;
		if (line.empty() || line[0] == ';' || line[0] == '#') {
			// 空行或注释行,忽略
			continue;
		}
		else if (line[0] == '[' && line[line.length() - 1] == ']') {
			// 新的节(section)
			currentSection = line.substr(1, line.length() - 2);
			//cout <<  "Section" << currentSection.c_str() << endl; 
		}
		else {
			// 键值对
			std::size_t equalsPos = line.find('=');
			if (equalsPos != std::string::npos) {
				std::string key = line.substr(0, equalsPos);
				std::string value = line.substr(equalsPos + 1);
				iniData[currentSection][key] = value;
			}
		}
	}

	file.close();
	return iniData;
}

int MyIni::FillReaderInfo(std::string section) {

	std::map<std::string, std::map<std::string, std::string>>::iterator it;

	std::map<std::string, std::string>::iterator it1;
	std::map<std::string, std::string> ma;

	
	it = iniData.find(section);
	if (it == iniData.end())
	{
		cout << "not find section " << section << endl;
		return -1;
	}
	else {
		cout << "find section " << section << endl;
		for (it1 = it->second.begin(); it1 != it->second.end(); it1++)
		{
			ma[it1->first] = it1->second;
		}
	}

#if 0
	for (it1 = ma.begin(); it1 != ma.end(); it1++)
	{
		cout << it1->first << "=" << it1->second << endl;
	}
#endif

	it1 = ma.find("chLineNumber");
	if (it1 == ma.end())
	{
		cout << "not find chLineNumber" << endl;
		return -1;
	}
}
//注意此例子文件打开格式要为LF

}
在这里插入图片描述
可以用noteped++打开修改,windows下面的需要稍微进行处理,去除末尾的\r \n两个字符


http://www.kler.cn/a/157707.html

相关文章:

  • 【腾讯云云上实验室】个人对腾讯云向量数据库的体验心得
  • 第一节JavaScript 简介与使用
  • springboot-技术栈汇总
  • 3.5毫米音频连接器接线方式
  • Linux scatterlist 详解
  • 【Filament】Filament环境搭建
  • @Scheduled,Quartz,XXL-JOB三种定时任务总结
  • java使用xstream框架生成xml文件
  • MySQL导出ER图为图片或PDF
  • uniapp 云打包 生成安卓证书文件
  • 【Redis实现全局唯一ID】
  • Linux lshw命令(lshw指令)(List Hardware,获取底层硬件信息)(查询硬件信息)
  • python中字符串的常用方法
  • PostgreSQL 连接更新操作
  • 京东数据分析(京东数据运营):2023年10月咖啡市场销售数据分析(商家销量销额店铺数据)
  • Flink 读写Doris
  • enum 枚举类型
  • 【openssl】RSA 生成公钥私钥 |通过私钥获取公钥
  • SpringBoot——嵌入式 Servlet容器
  • 如何判别使用的junit是4还是5