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

ini文件就是简单的section 下面有对应的键值对
C++ ini配置文件的简单读取使用_第1张图片

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

}
C++ ini配置文件的简单读取使用_第2张图片
可以用noteped++打开修改,windows下面的需要稍微进行处理,去除末尾的\r \n两个字符

你可能感兴趣的:(c++,开发语言)