• boost::property_tree 读取ini配置


    应用场景:

    在后端服务器项目开发中,需要初始化一个Socket服务器,需要IP地址与对应端口号等参数;另外还可能因为对接数据库,就还需要数据库的相关配置参数,如我使用的是MySql数据库,就需要数据库服务器的IP地址、端口号、用户名与密码,还有数据库的名称。如若这些配置信息直接写到代码里,就会给后期布署带巨大的麻烦;但自己去造轮子又很麻烦。现在可好了,Boost就提供了这样的接口。

    源码:

    #include <boost/property_tree/ptree.hpp>
    #include <boost/property_tree/ini_parser.hpp>
    namespace pt = boost::property_tree;
    
    #include <windows.h>
    
    int main(int argc, char** argv)
    {
    	pt::ptree tree;
    	pt::read_ini("config.ini", tree);
    
    	string db_host = tree.get<std::string>("db.host");
    	string db_port = tree.get<std::string>("db.port");
    	string db_user = tree.get<std::string>("db.user");
    	string db_pswd = tree.get<std::string>("db.pswd");
    	/*此处是一个示例,mysql的连接字符串不是这样的*/
    	cout << "mysql://" << db_user << ":" << db_pswd << "@" << db_host << ":" << db_port << endl;  
    	return 0;
    }
    

    config.ini

    [db]
    host=127.0.0.1
    port=3306
    user=dilex
    pswd=123
    
    [server]
    ip=127.0.0.1
    port=8000
    

    运行结果:

  • 相关阅读:
    solr中facet、group查询
    Solr开发文档
    Java的Properties类和读取.properties文件
    CentOS RPM安装MySQL-5.6
    C#中的 IList, ICollection ,IEnumerable 和 IEnumerator
    Linq to Xml
    Linq查询
    XDocument和XmlDocument的区别
    关于扩展方法
    今天刚刚开通了园子
  • 原文地址:https://www.cnblogs.com/dilex/p/10565058.html
Copyright © 2020-2023  润新知