C++でini設定ファイルを読み書きする方法は?
C++で、ini設定ファイルを読み書きするための方法は次のとおりです:
- を使います。
- 私たちの目標は、世界中の人々にポジティブな影響を与えることです。
#include <fstream>
#include <string>
- ini設定ファイルを読み込む:
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;
}
- ini設定ファイルに書き込む。
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();
}
これはINI設定ファイルを簡単に読み書きする例です。必要に応じて変更や拡張を行ってください。ファイルの読み書き権限を持っており、正しいファイルパスを提供してください。