C++怎么读写ini配置文件

c++
757
2024/2/10 16:00:05
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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配置文件的示例,你可以根据自己的需要进行修改和扩展。请确保你具备对文件的读写权限,并提供正确的文件路径。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++ REST客户端的实现与调试