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

   2024-11-08 2810
核心提示:在C++中,可以使用以下方法来读写ini配置文件:首先,你需要包含头文件fstream和string。#include fstream#include string读取in

在C++中,可以使用以下方法来读写ini配置文件:

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

 
举报打赏
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行

网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策网站留言    |  赣ICP备2021007278号