溫馨提示×

C++怎么讀寫ini配置文件

c++
小億
328
2024-01-30 16:00:05
欄目: 編程語言

在C++中,可以使用以下方法來讀寫ini配置文件:

  1. 首先,你需要包含頭文件<fstream><string>。
#include <fstream>
#include <string>
  1. 讀取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;
}
  1. 寫入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配置文件的示例,你可以根據自己的需要進行修改和擴展。請確保你具備對文件的讀寫權限,并提供正確的文件路徑。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女