boost::property_tree 读取ini配置

时间:2023-03-09 04:03:30
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

运行结果:

boost::property_tree 读取ini配置