首页 > 系统相关 >linux c++读写ini文件,不是用boost

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

时间:2024-02-01 13:56:22浏览次数:24  
标签:map string 文件 c++ 键值 ini linux include

摘自: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函数中测试了这两个函数,并打印了读取到的配置信息。

标签:map,string,文件,c++,键值,ini,linux,include
From: https://www.cnblogs.com/LiuYanYGZ/p/18001074

相关文章

  • Linux 安装 Mariadb(MySQL)
    使用如下命令查询当前linux发行版的信息:lsb_release-a接着安装Mariadb,命令:aptinstallmariadb-servermariadb-client安装 Mariadb之后依旧是使用mysql命令,它是mysql的分支而已设置root密码,执行:sudomysql_secure_installation然后提示Setrootpassword?[Y/n],输入Y......
  • Linux系统下使用dockercompose部署的stringboot应用程序不断重启,无法正常访问。
    Linux系统下使用dockercompose部署的stringboot应用程序不断重启,无法正常访问。问题描述使用dockercompose部署的stringboot应用程序,每次都是启动成功,通过apifox访问接口就失败,端口也无法ping通。没有任何报错信息,启动日志也不全,只有2行。最开始定位的是stringboot的版本号问题......
  • linux中9个常用的shell脚本
    注意事项1)开头加解释器:#!/bin/bash2)语法缩进,使用四个空格;多加注释说明。3)命名建议规则:变量名大写、局部变量小写,函数名小写,名字体现出实际作用。4)默认变量是全局的,在函数中变量local指定为局部变量,避免污染其他作用域。5)有两个命令能帮助我调试脚本:set-e遇到执行非0时退出脚本,set......
  • linux centos7+apache2+php
    Thisisbasicenvironmenttoservephpapplicationframework.Wedon'tneedaDatabaseinthiscase.MakeaserveroncentosEnvironmentSettingupsomeenvironment(phpandapacheenvironment)Touchthefileandpastetheweb-shellsamplecode.Chec......
  • linux用户组操作命令
    查看所有用户compgen是bash的内置命令,它将显示所有可用的命令,别名和函数。compgen-u查看当前用户属于那些组groups查看某个用户属于哪些组groups查看系统有哪些组getentgroup追加用户到新的用户组,让他处在多个组中-aG必须要加a,代表append,否则G会让用户脱离......
  • C++第五十五篇-定时器SetTimer
    使用的一个百度AI代码生成网站: https://yiyan.baidu.com/定时器的实现示例:新建一个程序 编写ConsoleApplication1.cpp#include<iostream>#include<Windows.h>usingnamespacestd;#pragmacomment(lib,"User32.lib")//首先定义一个计时器计时事件的定义#define......
  • 4、linux设置主机名
    linux设置主机名1、查看主机名hostname默认:localhost.localdomain2、更改主机名编辑/etc/hostname,修改成自己需要的主机名vi/etc/hostname3、设置hosts编辑/etc/hosts,将修改的主机名增加一个映射vi/etc/hosts/etc/hosts127.0.0.1localhostlocalhost.localdoma......
  • Linux下查询CPU,内存,磁盘及操作系统
    查询CPU核数nproc结果为4查询内存free-h#以人类(human)可读的方式展示结果为totalusedfreesharedbuff/cacheavailableMem:15Gi2.2Gi327Mi1.0Mi13Gi13GiSwap:......
  • 全流程机器视觉工程开发(四)PaddleDetection C++工程化应用部署到本地DLL以供软件调用
    前言我们之前跑了一个yolo的模型,然后我们通过PaddleDetection的库对这个模型进行了一定程度的调用,但是那个调用还是基于命令的调用,这样的库首先第一个不能部署到客户的电脑上,第二个用起来也非常不方便,那么我们可不可以直接将Paddle的库直接做成一个DLL部署到我们的软件上呢?答案是......
  • Windows环境安装配置Miniconda
    从官网下载安装Miniconda配置环境变量”此电脑“右击”属性“->”高级系统设置“->”高级“->”环境变量“->”系统变量“->”Path“->”编辑“”新建“->添加”路径\miniconda3“”新建“->添加”路径\miniconda3\Scripts“”新建“->添加”路径\miniconda3\Library\bin“......