C++ INI Parser: Read/Write Config Files
In C++, you can read and write ini configuration files using the following methods:
- file stream
- –
#include <fstream>
#include <string>
- Read the ini configuration file:
std::string GetValueFromIni(const std::string& filePath, const std::string& section, const std::string& key) {
std::ifstream file(filePath);
std::string line;
std::string value;
bool sectionFound = false;
while (std::getline(file, line)) {
// 如果找到了对应的section,则将sectionFound标记为true
if (line.find("[" + section + "]") != std::string::npos) {
sectionFound = true;
continue;
}
// 如果当前行包含key,则获取对应的value
if (sectionFound && line.find(key) != std::string::npos) {
// 从等号之后获取value
value = line.substr(line.find('=') + 1);
// 去掉value中的空格
value.erase(value.find_last_not_of(" \n\r\t") + 1);
break;
}
}
file.close();
return value;
}
- Write to an INI configuration file:
void SetValueToIni(const std::string& filePath, const std::string& section, const std::string& key, const std::string& value) {
std::ifstream file(filePath);
std::string line;
std::string content;
bool sectionFound = false;
bool keyFound = false;
while (std::getline(file, line)) {
// 如果找到了对应的section,则将sectionFound标记为true
if (line.find("[" + section + "]") != std::string::npos) {
sectionFound = true;
}
// 如果在对应的section中找到了key,则替换当前行为新的value
if (sectionFound && line.find(key) != std::string::npos) {
line = key + "=" + value;
keyFound = true;
}
content += line + "\n";
}
file.close();
// 如果section或key不存在,则在文件末尾添加新的section和key-value对
if (!sectionFound) {
content += "[" + section + "]\n";
content += key + "=" + value + "\n";
} else if (!keyFound) {
content += key + "=" + value + "\n";
}
std::ofstream outFile(filePath);
outFile << content;
outFile.close();
}
Here is a simple example of reading and writing an INI configuration file. Feel free to modify and expand it according to your needs. Make sure you have the necessary permission to read and write files and provide the correct file path.