首页 > 其他 > 详细

boost::property_tree 读取ini配置

时间:2019-03-20 16:19:14      阅读:484      评论:0      收藏:0      [点我收藏+]

应用场景:

在后端服务器项目开发中,需要初始化一个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

 

运行结果:

技术分享图片

 

boost::property_tree 读取ini配置

原文:https://www.cnblogs.com/dilex/p/10565058.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!