program_options读命令行和配置文件

#include <boost/program_options.hpp>
#include <string.h>
#include <iostream>
#include <fstream>
#include <map>

using namespace std;
using namespace boost;

namespace bpo = boost::program_options;

/*
config.ini:
p2p-endpoint = 0.0.0.1:31010

rpc-endpoint = 0.0.0.0:38090

*/
int main(int argc,char** argv)
{
cout << "cmd line:" << endl;
bpo::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("df_value", bpo::value<string>()->default_value("123"), ""); //give default

bpo::variables_map cmdValueMap;
bpo::store(bpo::parse_command_line(argc, argv, desc), cmdValueMap);
bpo::notify(cmdValueMap);

if(cmdValueMap.count("help")){
cout<<desc<<endl;
}
if(cmdValueMap.count("df_value")){
cout << "df_value:" << cmdValueMap["df_value"].as<string>() << endl;
}

cout << endl;
cout << "直接读取文件配置:" << endl;
boost::program_options::options_description options("Graphene Witness Node");
bpo::variables_map fileValueMap;
options.add_options()
("p2p-endpoint", bpo::value<string>(), "Endpoint for P2P node to listen on")
("rpc-endpoint", bpo::value<string>(),"aaa")
("genesis-json", bpo::value<string>()->default_value("my-genesis.json"),"genesis-json");

bool useIfStream = true;//both is ok
if(useIfStream)
{
ifstream ifs("config.ini");
boost::program_options::store(boost::program_options::parse_config_file(ifs,options), fileValueMap);
}else
{
boost::program_options::store(boost::program_options::parse_config_file<char>("config.ini",options, true), fileValueMap);
}
boost::program_options::notify(fileValueMap);

if(fileValueMap.count("p2p-endpoint")){
cout << fileValueMap["p2p-endpoint"].as<string>() << endl;
}
if(fileValueMap.count("rpc-endpoint")){
cout << fileValueMap["rpc-endpoint"].as<string>() << endl;
}
if(fileValueMap.count("genesis-json")){
cout << fileValueMap["genesis-json"].as<string>() << endl;
}

cout << endl;
cout << "遍历valueMap:" << endl;
for(bpo::variables_map::iterator iter = fileValueMap.begin(); iter != fileValueMap.end(); ++iter){
cout << iter->first << ":" << iter->second.as<string>() << endl;
}
}


执行:./a.out --help

cmd line:
Allowed options:
--help produce help message
--df_value arg (=123)

df_value:123

直接读取文件配置:
0.0.0.1:31010
0.0.0.0:38090
my-genesis.json

遍历valueMap:
genesis-json:my-genesis.json
p2p-endpoint:0.0.0.1:31010
rpc-endpoint:0.0.0.0:38090
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值