linux 使用iniparser读取.ini文件的配置信息

为什么要用项目配置文件

对于很多程序中要用的参数如果是可变的,那么最好的处理方式就是通过main(int argc,char **argv) 函数参数传递,或者从别的地方去获取,这其中之一就是配置文件,但是在一个成熟和架构完善的系统,一般都会做到自动配置,自动部署,所以有的系统里会有一个单独的配置服务存在,每个其它的服务的配置信息从配置中心服务
获取,然后运维人员通过操作界面把配置信息下发给配置中心服务.几乎每一个大型互联网项目都会涉及到项目配置

1安装第三方开源的iniparser

git clone https://github.com/ndevilla/iniparser

cd iniparser

make

在这里插入图片描述
在这里插入图片描述

使用iniparser编译选项
-liniparser

2 设置配置 .ini 信息

server.ini

[tabase]
ip = 127.0.0.1;
port = 3306;
user = root;
pwd = 12345678;
db = ReadIni;

[server]
port = 8888;

3 创建配置文件结构体

configdef.h

#ifndef SHBK_COMMON_INICONFIG_H
#define SHBK_COMMON_INICONFIG_H

#include <string>

typedef struct st_env_config {
        //数据库配置
        std::string db_ip;      //数据库ip
        unsigned short db_port; //数据库端口号
        std::string db_user;    //数据库用户名
        std::string db_pwd;     //数据库用密码
        std::string db_name;    //数据库名称

        //服务器的配置
        unsigned short svr_port;//服务器端口号

        st_env_config() {};

        st_env_config(const std::string& db_ip, unsigned short db_port,
                const std::string& db_user, const std::string& db_pwd,
                const std::string& db_name, unsigned short svr_port)
        {
                this->db_ip = db_ip;
                this->db_port = db_port;
                this->db_user = db_user;
                this->db_pwd = db_pwd;
                this->db_name = db_name;
                this->svr_port = svr_port;
        };

        st_env_config& operator=(const st_env_config& config)
        {
                if (this != &config)
                {
                        this->db_ip = config.db_ip;
                        this->db_port = config.db_port;
                        this->db_user = config.db_user;
                        this->db_pwd = config.db_pwd;
                        this->db_name = config.db_name;
                        this->svr_port = config.svr_port;
                }
                return *this;
        }

}_st_env_config;
#endif // !SHBK_COMMON_IN

4 将 获取配置信息 & 初始化配置信息 封装成类

iniconfig.h

#ifndef SHBK_COMMON_INICONFIG_H_
#define SHBK_COMMON_INICONFIG_H_
#include <string>
#include "configdef.h"

class Iniconfig
{
public:
        Iniconfig();
        ~ Iniconfig();
        //加载配置文件
        bool loadfile(const std::string& path);
        //获取配置项
        const _st_env_config& getconfig();

private:
        _st_env_config   _config;       //配置文件
        bool            _isloaded;      //是否加载了配置文件
};
#endif // SHBK_COMMON_INICONFIG_H_

iniconfig.cpp

#include "iniconfig.h"
#include <iniparser/iniparser.h>

Iniconfig::Iniconfig():_isloaded(false)
{}

Iniconfig::~Iniconfig()
{}

bool Iniconfig::loadfile(const std::string& path)
{
    dictionary* ini = NULL;
    if (!_isloaded)
    {
        ini = iniparser_load(path.c_str());
        if (ini == NULL) {
            fprintf(stderr, "cannot parse file: %s\n", path.c_str());
            return -1;
        }
        
        const char* ip   = iniparser_getstring(ini, "tabase:ip",   "127.0.0.1");
        int         port = iniparser_getint   (ini, "tabase:port", 3306 );
        const char* user = iniparser_getstring(ini, "tabase:user", "root");
        const char* pwd  = iniparser_getstring(ini, "tabase:pwd",  "12345678");
        const char* db   = iniparser_getstring(ini, "tabase:db",   "ReadIni");
        int         sport= iniparser_getint   (ini, "server:port", 8888);

        _config = _st_env_config(std::string(ip), 
        						port, std::string(user),std::string(pwd), std::string(db),sport);
        
        iniparser_freedict(ini);

        _isloaded = true;	
        return true;
    }
}

const _st_env_config& Iniconfig::getconfig()
{
    return _config;
}

5读取配置信息

main.cpp

#include <stdio.h>
#include "iniconfig.h"
#include "configdef.h"

int main(int argc, char* argv[]) {
    if (argc != 2)//传入参数不合法
    {
        printf("Please input format <your process> <.ini file path>\n");
        return -1;
    }
    
    Iniconfig config;//配置文件加载信息
    if (!config.loadfile(std::string(argv[1]))) //配置文件加载失败
    {
        printf("load %s failed.\n", argv[1]);
        return -2;
    }

    _st_env_config conf_args = config.getconfig();
    printf("[tabase] ip:%s port:%d user:%s pwd:%s db:%s [server]port:%d\n",
        conf_args.db_ip.c_str(),    conf_args.db_port,             conf_args.db_user.c_str(),
        conf_args.db_pwd.c_str(),   conf_args.db_name.c_str(),     conf_args.svr_port
    );
   return 0;
}

6使用CMake编译此项目

在main.cpp 所在文件创建/third/include 和 /third/lib目录存放头文件和库
将头文件和库分别复制创建的目录中

CMakeLists.txt

#指定版本号
CMAKE_MINIMUM_REQUIRED(VERSION  3.5)
#工程名
PROJECT(ini_demo)
#将指定的目录头文件添加到编译器的头文件搜索路径之下
INCLUDE_DIRECTORIES(./third/include)

#将指定的目录库文件添加需要链接的库文件目录之下
LINK_DIRECTORIES(./third/lib/iniparser)


#内置变量:CMAKE_SOURCE_DIR 定义了顶级CMakeLists.txt 所在文件夹
#PROJECT_SOURCE_DIR定义了包含project()命令的CmakeLists.txt所在的文件夹
#搜集所有在指定路径下的源文件名,将输出结果储存在指定的变量中
aux_source_directory(${PROJECT_SOURCE_DIR} SOURCE_FILES)

#使用给定的源文件,为工程引入一个可执行文件
ADD_EXECUTABLE(ini_demo  ${SOURCE_FILES})

#用来显示的定义变量
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic -Wall -g3 -m64 -pipe -std=c++0x -lrt -Wno-reorder -Wdeprecated-declarations -fpermissive ")

#该指令的作用为目标文件与库文件进行链接
TARGET_LINK_LIBRARIES(ini_demo  iniparser)
target_link_libraries(ini_demo  pthread)

#设置默认安装目录
SET(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR})

#安装
INSTALL(TARGETS ini_demo DESTINATION bin)

cmake .
make

在这里插入图片描述
执行程序
在这里插入图片描述

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江凡心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值