C++实现读写ini配置文件的示例代码

目录
  • 1.概述
  • 2.ini格式语法
  • 3.配置读取
  • 4.demo示例
  • 5.自动生成读取代码

1.概述

配置文件的读取是每个程序必备的功能,配置文件的格式多种多样,例如:ini格式、json格式、xml格式等。其中属ini格式最为简单,且应用广泛。

2.ini格式语法

  • 注释内容采用“#”或者“;”开头。
  • 配置是由一系列的section组成,每个section就是一个关联的配置块,section使用[]包含起来。
  • 每个section下配置的是具体的配置项,每个配置项是使用“=”分隔的key-value对。

下面让我们来看一个简单的示例,假设我们有一个配置文件demo.cfg,它的内容如下所示。

[server]
ip = 127.0.0.1
port = 8088

上面的配置内容中,有一个server的配置节,在这个配置节里有两个配置项,它们分别是ip和port,ip的值为127.0.0.1,port的值为8088。

3.配置读取

知道了ini格式语法之后,就可以根据语法规则来读取配置文件内容了,春哥这里实现了一个非常精简易用的版本,源代码文件config.hpp的内容如下。

#pragma once

#include <fstream>
#include <functional>
#include <string>
#include <unordered_map>

namespace Config {
class Ini {
 public:
  void Dump(std::function<void(const std::string&, const std::string&, const std::string&)> deal) {
    auto iter = cfg_.begin();
    while (iter != cfg_.end()) {
      auto kv_iter = iter->second.begin();
      while (kv_iter != iter->second.end()) {
        deal(iter->first, kv_iter->first, kv_iter->second);
        ++kv_iter;
      }
      ++iter;
    }
  }
  bool Load(std::string file_name) {
    if (file_name == "") return false;
    std::ifstream in;
    std::string line;
    in.open(file_name.c_str());
    if (not in.is_open()) return false;
    while (getline(in, line)) {
      std::string section, key, value;
      if (not parseLine(line, section, key, value)) {
        continue;
      }
      setSectionKeyValue(section, key, value);
    }
    return true;
  }
  void GetStrValue(const std::string& section, const std::string& key, std::string& value, std::string default_value) {
    value = default_value;
    if (cfg_.find(section) == cfg_.end()) {
      return;
    }
    if (cfg_[section].find(key) == cfg_[section].end()) {
      return;
    }
    value = cfg_[section][key];
  }
  void GetIntValue(const std::string& section, const std::string& key, int64_t& value, int64_t default_value) {
    value = default_value;
    if (cfg_.find(section) == cfg_.end()) {
      return;
    }
    if (cfg_[section].find(key) == cfg_[section].end()) {
      return;
    }
    value = atol(cfg_[section][key].c_str());
  }

 private:
  void ltrim(std::string& str) {
    if (str.empty()) return;
    size_t len = 0;
    char* temp = (char*)str.c_str();
    while (*temp && isblank(*temp)) {
      ++len;
      ++temp;
    }
    if (len > 0) str.erase(0, len);
  }
  void rtrim(std::string& str) {
    if (str.empty()) return;
    size_t len = str.length();
    size_t pos = len;
    while (pos > 0) {
      if (not isblank(str[pos - 1])) {
        break;
      }
      --pos;
    }
    if (pos != len) str.erase(pos);
  }
  void trim(std::string& str) {
    ltrim(str);
    rtrim(str);
  }
  void setSectionKeyValue(std::string& section, std::string& key, std::string& value) {
    if (cfg_.find(section) == cfg_.end()) {
      std::unordered_map<std::string, std::string> kv_map;
      cfg_[section] = kv_map;
    }
    if (key != "" && value != "") cfg_[section][key] = value;
  }
  bool parseLine(std::string& line, std::string& section, std::string& key, std::string& value) {
    static std::string cur_section = "";
    std::string nodes[2] = {"#", ";"};  //去掉注释的内容
    for (int i = 0; i < 2; ++i) {
      std::string::size_type pos = line.find(nodes[i]);
      if (pos != std::string::npos) line.erase(pos);
    }
    trim(line);
    if (line == "") return false;
    if (line[0] == '[' && line[line.size() - 1] == ']') {
      section = line.substr(1, line.size() - 2);
      trim(section);
      cur_section = section;
      return false;
    }
    if (cur_section == "") return false;
    bool is_key = true;
    for (size_t i = 0; i < line.size(); ++i) {
      if (line[i] == '=') {
        is_key = false;
        continue;
      }
      if (is_key) {
        key += line[i];
      } else {
        value += line[i];
      }
    }
    section = cur_section;
    trim(key);
    trim(value);
    return true;
  }

 private:
  std::unordered_map<std::string, std::unordered_map<std::string, std::string>> cfg_;
};  // ini格式配置文件的读取
}  // namespace Config

Config命名空间下实现了Ini配置读取类。Load函数用于加载配置文件内容,GetStrValue函数和GetIntValue函数用于获取配置项值并支持设置默认值,Dump函数用于遍历配置文件的内容。由于在解析过程中需要删除字符串中的前导和后导空白符,因此我们还实现了trim函数用于删除前导和后导空白符。

这里重点讲解一下Load函数的逻辑:每次从配置文件中读取一行,然后先去掉注释的内容,接着再判断剩余的内容是一个section头配置,还是section下的key-value配置,再走不同的解析分支。

4.demo示例

以上面配置文件demo.cfg内容的读取为例,示例代码如下。

#include <iostream>

#include "config.hpp"

int main(int argc, char *argv[]) {
  Config::Ini ini;
  ini.Load("./demo.cfg");
  ini.Dump([](const std::string &section, const std::string &key, const std::string value) {
    std::cout << "section[" << section << "],key[" << key << "]->value[" << value << "]" << std::endl;
  });
  return 0;
}

5.自动生成读取代码

如果这次分享的内容到上面demo示例之后就进入尾声的话,那么春哥就太过于标题党了。假设我们的程序有几十项配置内容,如果每一项采用GetIntValue函数或者GetStrValue函数来读取,那么编码工作量还是不小的,并且也容易出错,那么怎么做到提效呢?

其实提效方案并不难想到,我们可以自动生成读取配置项的代码,并生成具体业务配置读取类。下面我们举一个例子,假设我们有一个配置文件mysvr.cfg,它的内容如下。

[server]
ip = 127.0.0.1
port = 8080

[pool]
conn_pool_size = 100

我们手动编写了业务配置读取类代码文件MySvrCfg.hpp,它的内容如下。

#include <string>

#include "config.hpp"

class MysvrCfg {
 public:
  bool Load(std::string file_name) {
    Config::Ini ini;
    if (not ini.Load(file_name)) {
      return false;
    }
    ini.GetIntValue("pool", "conn_pool_size", conn_pool_size_, 0);
    ini.GetIntValue("server", "port", port_, 0);
    ini.GetStrValue("server", "ip", ip_, "");

    return true;
  }
  int64_t conn_pool_size() { return conn_pool_size_; }
  int64_t port() { return port_; }
  std::string ip() { return ip_; }

 public:
  int64_t conn_pool_size_;
  int64_t port_;
  std::string ip_;
};

我们可以发现上面的代码完全可以自动生成。「我们先读取配置的内容,然后使用配置文件的内容作为元数据驱动生成这个MySvrCfg.hpp的内容」。

自动生成业务配置读取类的脚手架工具代码文件configtool.cpp,它的内容如下。

#include <iostream>
#include <regex>
#include <string>

#include "MysvrCfg.hpp"

using namespace std;

int genCfgReadFile(Config::Ini &ini, string file_name) {
  string prefix = "";
  for (size_t i = 0; i < file_name.size(); i++) {
    if (file_name[i] == '.') break;
    if (prefix == "") {
      prefix = toupper(file_name[i]);
    } else {
      prefix += file_name[i];
    }
  }
  string class_name = prefix + "Cfg";
  string output_file_name = prefix + "Cfg.hpp";
  ofstream out;
  out.open(output_file_name);
  if (not out.is_open()) {
    cout << "open " << output_file_name << " failed." << endl;
    return -1;
  }
  string cfg_read_content;
  string class_func_content;
  string class_member_content;
  ini.Dump([&cfg_read_content, &class_func_content, &class_member_content](const string &section, const string &key,
                                                                           const string &value) {
    regex integer_regex("[+-]?[0-9]+");
    if (regex_match(value, integer_regex)) {  // 整数
      cfg_read_content += "    ini.GetIntValue("" + section + "", "" + key + "", " + key + "_, 0);\n";
      class_func_content += "  int64_t " + key + "() { return " + key + "_; }\n";
      class_member_content += "  int64_t " + key + "_;\n";
    } else {
      cfg_read_content += "    ini.GetStrValue("" + section + "", "" + key + "", " + key + "_, "");\n";
      class_func_content += "  std::string " + key + "() { return " + key + "_; }\n";
      class_member_content += "  std::string " + key + "_;\n";
    }
  });
  //
  string content = R"(#include <string>

#include "config.hpp"

class )" + class_name +
                   R"( {
 public:
  bool Load(std::string file_name) {
    Config::Ini ini;
    if (not ini.Load(file_name)) {
      return false;
    }
)" + cfg_read_content +
                   R"(
    return true;
  }
)" + class_func_content +
                   R"(
 public:
)" + class_member_content +
                   "};";
  out << content;
  return 0;
}

int readDemoCfg() {
  MysvrCfg cfg;
  cout << "usage: configtool cfg_file_name" << endl;
  cout << "read demo cfg mysvr.cfg" << endl;
  cfg.Load("./mysvr.cfg");
  cout << "ip = " << cfg.ip() << endl;
  cout << "port = " << cfg.port() << endl;
  cout << "conn_pool_size = " << cfg.conn_pool_size() << endl;
  return 0;
}

int main(int argc, char *argv[]) {
  if (argc == 1) {
    return readDemoCfg();
  }
  if (argc != 2) {
    cout << "usage: configtool mysvr.cfg" << endl;
    return -1;
  }
  Config::Ini ini;
  string file_name = argv[1];
  if (not ini.Load(file_name)) {
    cout << "load " << file_name << " failed." << endl;
    return -1;
  }
  return genCfgReadFile(ini, file_name);
}

在configtool脚手架工具中,「我们先使用Config::Ini类对象读取了配置文件的内容,然后遍历配置文件的内容,生成业务配置读取类中动态变化的代码内容,最后使用模版生成最终的代码」。

脚手架工具configtool的使用也非常简单,直接把配置文件名作为命令行参数传入即可,如果执行configtool时不携带任何参数则会使用生成的类MysvrCfg来读取上面的配置文件mysvr.cfg的内容。

到此这篇关于C++实现读写ini配置文件的示例代码的文章就介绍到这了,更多相关C++读写ini配置文件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++读取INI配置文件类实例详解

    本文以实例讲解了C++读取配置文件的方法. 一般情况下,我们都喜欢使用ini扩展名的文件作为配置文件,可以读取及修改变量数值,也可以设置新的组,新的变量,本文的实例代码一个是读取INI的定义文件,另一个是CIniFile类实现文件,两者结合,完美实现VC++对INI文件的读写. 用户接口说明:在成员函数SetVarStr和SetVarInt函数中,当iType等于零,则如果用户制定的参数在ini文件中不存在,则就写入新的变量.当iType不等于零,则如果用户制定的参数在ini文件中不存在,就不写

  • C/C++ INI文件操作实现代码

    一.INI文件用途: 1.存储程序的初始化信息: 2.存储需要保存的数据信息. 二.INI文件结构: 由节名.键名.键值组成.形式如下: [节名] 键名 = 键值 备注:一个INI文件,可以用多个节. 三.读取INI文件 1.WritePrivateProfileString 该函数用于向INI文件中写入一个字符串数据. 函数原型如下: BOOL WritePrivateProfileString( LPCTSTR lpAppName, // pointer to section name LP

  • C++实现ini文件读写的示例代码

    目录 介绍 1.使用INIReader.h头文件 1.INIReader.h 2.test.ini 3.INIReaderTest.cpp 2.使用ini.h头文件 1.ini.h 2.config.ini 3.example.cpp 3.使用inipp.h头文件 3.1 解析算法 3.2 默认section算法 3.3 Interpolation算法 3.4 代码实现 介绍 一般的ini配置文件由节.键.值组成. [参数](键=值),例如 :key=value; [节]:所有的参数都是以节(s

  • C++读写INI配置文件的类实例

    本文实例讲述了C++读写INI配置文件的类.分享给大家供大家参考.具体如下: 1. IniReader.h文件: #ifndef INIREADER_H #define INIREADER_H #include <windows.h> class CIniReader { public: CIniReader(LPCTSTR szFileName); int ReadInteger(LPCTSTR szSection, LPCTSTR szKey, int iDefaultValue); fl

  • C语言Iniparser库实现ini文件读写

    目录 一.概述 二.使用 下载 方式一 方式二 三.API函数 四.演示 一.概述 iniparser是针对INI文件的解析器.ini文件则是一些系统或者软件的配置文件.iniparser库的API可以对ini文件(配置文件)进行解析.设置.删除等操作. 常见的 ini 读写开源库有:minIni.inifile.iniparser 二.使用 下载 Github:https://github.com/ndevilla/iniparser 方式一 1.编译 下载后进入文件根目录,使用 make 命

  • C++读写ini配置文件实现过程详解

    在Windows的VC下 读ini文件 例如:在D:\test.ini文件中 [Font] name=宋体 size= 12pt color = RGB(255,0,0) 上面的=号两边可以加空格,也可以不加 用GetPrivateProfileInt()和GetPrivateProfileString() [section] key=string . . 获取integer UINT GetPrivateProfileInt( LPCTSTR lpAppName, // section nam

  • java 读写 ini 配置文件的示例代码

    下面通过代码先看下java 读写 ini 配置文件,代码如下所示: package org.fh.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URLDecoder; import java.util.regex.

  • Python3读写ini配置文件的示例

    ini文件即Initialization File初始化文件,在应用程序及框架中常作为配置文件使用,是一种静态纯文本文件,使用记事本即可编辑. 配置文件的主要功能就是存储一批变量和变量值,在ini文件中使用[章(Section)]对变量进行了分组,基本格式如下. # filename: config.ini [user] name=admin password=123456 is_admin=true [mysql] host=10.10.10.10 port=3306 db=apitest u

  • Windows系统中C#读写ini配置文件的程序代码示例分享

    最近接触到INI配置文件的读写,虽然很久以前微软就推荐使用注册表来代替INI配置文件,现在在Visual Studio上也有专门的.Net配置文件格式,但是看来看去还是INI配置文件顺眼.事实上.Net的XML格式配置文件在功能上更加强大,我也更推荐大家使用这种类型的配置文件来进行.Net软件的开发,我之所以使用INI配置文件,无非是想尝一下鲜和个人习惯而已. C#本身没有提供访问INI配置文件的方法,但是我们可以使用WinAPI提供的方法来处理INI文件的读写,代码很简单!网上有大量现成的代码

  • Python实现读写INI配置文件的方法示例

    本文实例讲述了Python实现读写INI配置文件的方法.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import ConfigParser import os '''读写配置文件的类 [section] logpath = D:\log\ imageminsize = 200 ''' class ConfigFile: '''构造函数:初始化''' def __init__(self,fileName): fileName = unicode(fileNam

  • C#中读写INI配置文件的方法

    在作应用系统开发时,管理配置是必不可少的.例如数据库服务器的配置.安装和更新配置等等.由于Xml的兴起,现在的配置文件大都是以xml文档来存储.比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介绍Remoting中提到的配置文件,都是xml的格式. 传统的配置文件ini已有被xml文件逐步代替的趋势,但对于简单的配置,ini文件还是有用武之地的.ini文件其实就是一个文本文件,它有固定的格式,节Section

  • C++读取配置文件的示例代码

    代码地址 https://github.com/gongluck/Code-snippet/tree/master/cpp/config 需求 开发中,读取配置文件信息必不可少.Windows平台有现成的API可用,也很方便.但是一旦项目迁移到Linux平台下,原先在Windows平台下的代码就全部作废.所以,实现一套跨平台的配置文件读取功能代码可以节省不少的劳动力. 实现 依赖于boost的ini_parser,可以实现跨平台读取ini格式的配置文件. // config.h /* * @Au

  • SpringBoot+Mybatis-Plus实现mysql读写分离方案的示例代码

    1. 引入mybatis-plus相关包,pom.xml文件 2. 配置文件application.property增加多库配置 mysql 数据源配置 spring.datasource.primary.jdbc-url=jdbc:mysql://xx.xx.xx.xx:3306/portal?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=

  • python读写ini配置文件方法实例分析

    本文实例讲述了python读写ini配置文件方法.分享给大家供大家参考.具体实现方法如下: import ConfigParser import os class ReadWriteConfFile: currentDir=os.path.dirname(__file__) filepath=currentDir+os.path.sep+"inetMsgConfigure.ini" @staticmethod def getConfigParser(): cf=ConfigParser

  • QT中如何读写ini配置文件

    如图1所示,我们需要在QT界面中实现手动读取参数存放的位置,那么我们该如何做呢? 方法:读取ini格式的配置文件,实现路径的写入与读取. 第一步:界面构造函数中,初始化一个Config.ini文件 //初始化一个.ini配置文件 //qApp是QT系统自带的,可以直接使用 QString iniFilePath=qApp->applicationDirPath()+"/Config.ini"; //如果不存在Config.ini,便生成一个Config.ini.如果已经存在了,则

随机推荐

其他