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 @ 2024-02-01 13:52  LiuYanYGZ  阅读(78)  评论(0编辑  收藏  举报