boost库
调用boost库的函数
使用boost库读取ini配置文件
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/ini_parser.hpp"
/// 读取ini配置文件数据
bool readIni(const std::string iniPath)
{
try {
boost::property_tree::ptree pt;
// 使用 ini_parser 解析 INI 文件
boost::property_tree::ini_parser::read_ini(iniPath, pt);
// 读取配置项并输出
int outdate_hour = pt.get<int>("PPTN.outdate_hour");
std::string orm_warn_str = pt.get<std::string>("PPTN.warn_orm");
std::string orm_data_str = pt.get<std::string>("PPTN.data_orm");
std::string task_id = pt.get<std::string>("task.task_id");
std::string clock_svr_addr = pt.get<std::string>("clock.svr_addr");
int flood_retry = pt.get<int>("PPTN.flood_retry");
int running_mode = pt.get<int>("PPTN.warn_method");
int running_interval = pt.get<int>("PPTN.running_interval");
int warning_rule_method = pt.get<int>("PPTN.warn_rule_method");
std::string addr = pt.get<std::string>("publish.pub_addr");
std::string port = pt.get<std::string>("publish.pub_port");
std::string redispwd = pt.get<std::string>("publish.pub_pwd");
}
catch (boost::property_tree::ptree_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return true;
}
int main()
{
std::string inipath = "./form.ini";
readIni(inipath);
return 0;
}
配置文件内容为
[clock]
svr_addr = 192.168.0.181:8081
[task]
task_id = 54476284
[publish]
# redis: 0; kafka : 1
pub_type = 0
pub_addr = 192.168.0.180
pub_port = 8080
pub_pwd = 123
pub_channel = warning_added,warning_status_changed
[PPTN]
# 1 通过加权平均 2 通过与关联站的最大值比价
warn_rule_method = 1
warn_method = 2
flood_retry = 0
running_interval = 10
outdate_hour= 2
warn_orm = mssql
data_orm = oracle
使用boost库直接底层修改
因为boost库在处理当节点名称带有.
符号的时候会出现无法成功读取的情况,boost库中实质就是一个map直接用find来查找即可
// 读取
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/ini_parser.hpp"
/// 读取ini配置文件数据
bool readIni(const std::string iniPath)
{
try {
boost::property_tree::ptree pt_tree;
// 使用 ini_parser 解析 INI 文件
boost::property_tree::ini_parser::read_ini(iniPath, pt_tree);
// int类型
std::string section = "PPTN";
std::string property = "outdate_hour";
boost::optional<int> i_value;
auto sectionIt = pt_tree.find(section);
if (sectionIt != pt_tree.not_found())
{
auto& sectionNode = sectionIt->second;
auto propertyIt = sectionNode.find(property);
if (propertyIt != sectionNode.not_found())
{
i_value = propertyIt->second.get_value_optional<int>();
}
}
// string类型
std::string section_2 = "task";
std::string property_2 = "task_id";
boost::optional<std::string> str_value;
auto sectionIt_2 = pt_tree.find(section_2);
if (sectionIt_2 != pt_tree.not_found())
{
auto& sectionNode = sectionIt_2->second;
auto propertyIt = sectionNode.find(property_2);
if (propertyIt != sectionNode.not_found())
{
str_value = propertyIt->second.get_value_optional<std::string>();
}
}
}
catch (boost::property_tree::ptree_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return true;
}
int main()
{
std::string inipath = "./form.ini";
readIni(inipath);
return 0;
}