C++鎬庝箞璇诲啓ini閰嶇疆鏂囦欢
鍦–++涓紝鍙互浣跨敤浠ヤ笅鏂规硶鏉ヨ鍐檌ni閰嶇疆鏂囦欢锛?/p>
- 棣栧厛锛屼綘闇€瑕佸寘鍚ご鏂囦欢
<fstream>鍜?code><string>銆?/li>
#include <fstream>
#include <string>
- 璇诲彇ini閰嶇疆鏂囦欢锛?/li>
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锛屽垯灏唖ectionFound鏍囪涓簍rue
if (line.find("[" + section + "]") != std::string::npos) {
sectionFound = true;
continue;
}
// 濡傛灉褰撳墠琛屽寘鍚玨ey锛屽垯鑾峰彇瀵瑰簲鐨剉alue
if (sectionFound && line.find(key) != std::string::npos) {
// 浠庣瓑鍙蜂箣鍚庤幏鍙杤alue
value = line.substr(line.find('=') + 1);
// 鍘绘帀value涓殑绌烘牸
value.erase(value.find_last_not_of(" \n\r\t") + 1);
break;
}
}
file.close();
return value;
}
- 鍐欏叆ini閰嶇疆鏂囦欢锛?/li>
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锛屽垯灏唖ectionFound鏍囪涓簍rue
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鎴杒ey涓嶅瓨鍦紝鍒欏湪鏂囦欢鏈熬娣诲姞鏂扮殑section鍜宬ey-value瀵?/span>
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閰嶇疆鏂囦欢鐨勭ず渚嬶紝浣犲彲浠ユ牴鎹嚜宸辩殑闇€瑕佽繘琛屼慨鏀瑰拰鎵╁睍銆傝纭繚浣犲叿澶囧鏂囦欢鐨勮鍐欐潈闄愶紝骞舵彁渚涙纭殑鏂囦欢璺緞銆?/p>