0
点赞
收藏
分享

微信扫一扫

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

举报

相关推荐

0 条评论