linux c++读写ini文件,不是用boost

摘自:https://linuxcpp.0voice.com/?id=65276

可以使用标准库中的fstream和string类来读写ini文件。

以下是一个示例代码:

复制代码
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
using namespace std;
// 解析ini文件,返回一个键值对的map
map<string, string> parseIniFile(const string& filename) {
    map<string, string> result;
    ifstream ifs(filename);
    if (!ifs.is_open()) {
        cerr << "Cannot open file: " << filename << endl;
        return result;
    }
    string line;
    string currentSection;
    while (getline(ifs, line)) {
        // 去掉空格和注释
        line = line.substr(0, line.find_first_of(';'));
        for (auto& c : line) {
            c = tolower(c);  // 转成小写方便比较
        }
        if (line.empty()) {
            continue;  // 空行
        } else if (line[0] == '[' && line.back() == ']') {
            currentSection = line.substr(1, line.size() - 2);
            continue;  // 新节
        } else {
            auto pos = line.find('=');
            if (pos == string::npos) {
                continue;  // 没有等号,忽略该行
            }
            auto key = currentSection + "." + line.substr(0, pos);
            auto value = line.substr(pos + 1);
            result[key] = value;
        }
    }
    return result;
}
// 将键值对写入ini文件中,如果文件不存在则新建文件
bool writeIniFile(const map<string, string>& data, const string& filename) {
    ofstream ofs(filename);
    if (!ofs.is_open()) {
        cerr << "Cannot open file: " << filename << endl;
        return false;
    }
    string currentSection;
    for (const auto& pair : data) {
        auto pos = pair.first.find('.');
        if (pos == string::npos) {
            continue;  // 没有节名,忽略该键值对
        }
        auto section = pair.first.substr(0, pos);
        auto key = pair.first.substr(pos + 1);
        if (section != currentSection) {
            ofs << "[" << section << "]" << endl;
            currentSection = section;
        }
        ofs << key << "=" << pair.second << endl;
    }
    return true;
}
int main() {
    // 测试读取ini文件
    auto data = parseIniFile("config.ini");
    cout << "Data read from config.ini:" << endl;
    for (const auto& pair : data) {
        cout << pair.first << "=" << pair.second << endl;
    }
    // 测试写入ini文件
    data["database.hostname"] = "localhost";
    data["database.username"] = "root";
    data["database.password"] = "123456";
    bool success = writeIniFile(data, "new_config.ini");
    if (success) {
        cout << "New configuration saved to new_config.ini." << endl;
    }
    return 0;
}
复制代码

 

g++         -std=c++11      1.cpp

 

这段代码定义了两个函数parseIniFile和writeIniFile来分别读取和写入ini文件。它们都使用标准库中的fstream和string类。

其中,parseIniFile函数接收一个文件名作为参数,返回一个map<string, string="">类型的键值对。该函数会依次读取文件中的每一行,忽略注释和空格,解析出节名和键值对,并将其存储在map中返回。注意,本代码假设所有节都是唯一的,并且键名不重复。

writeIniFile函数接收一个键值对的map和一个文件名作为参数,将该map中的数据写入到ini文件中。如果文件不存在,则新建一个文件。注意,本代码没有实现删除或修改键值对的功能。

最后,在main函数中测试了这两个函数,并打印了读取到的配置信息。

posted @   LiuYanYGZ  阅读(417)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-02-01 13. 散列表(中):如何打造一个工业级水平的散列表
2021-02-01 面试官:如何实现一个工业级的哈希表?
2021-02-01 pthread_getspecific和pthread_setspecific使用
2021-02-01 工业互联为何需要TSN?且先看这15个问题
点击右上角即可分享
微信分享提示