扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

C++鎬庝箞璇诲啓ini閰嶇疆鏂囦欢

扬州沐宇科技
2024-01-30 16:00:05
c++

鍦–++涓紝鍙互浣跨敤浠ヤ笅鏂规硶鏉ヨ鍐檌ni閰嶇疆鏂囦欢锛?/p>

  1. 棣栧厛锛屼綘闇€瑕佸寘鍚ご鏂囦欢<fstream>鍜?code><string>銆?/li>
#include <fstream>
#include <string>
  1. 璇诲彇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;
}
  1. 鍐欏叆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>

扫码添加客服微信