Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ boost::program_options reading arguments compatible with getopt_long

I'm developing an update in an existing program. I'm replacing Posix's getopt_long() with boost::program_options. But my work doesn't work as I should: I want to have read arguments like:

-server=www.example.com
-c config.txt

I was trying many possibilities from boost::program_options::command_line_style, but I can't find combinations which would give behaviour equal to getopt_long.

I found out that for arguments:

-server=www.example.com

I need flags:

command_line_style::allow_long_disguise | command_line_style::long_allow_adjacent

but I have problems with founding flags for:

-c config.txt

I found that flags:

command_line_style::allow_short | command_line_style::allow_dash_for_short | command_line_style::short_allow_next

give me almost what I want. Almost because:

ProgramOptionsParserTest.cpp:107: Failure
Value of: params.config
  Actual: " config.txt"
Expected: expectedParams.config
Which is: "config.txt"

so after using boost::algorithm::trim() it will be as I want.

So my question is: is it possible to handle arguments like -c config.txt with boost::program_options but without boost::algorithm::trim()?

EDIT I noticed that flags above don't work with unregistered arguments. I have registered options:

  programOptionsDescription.add_options()
      ("help,h", "display help message")
      ("config,c", value<std::string>(), "use configfile")
      ("server,s", value<std::string>(), "server")
      ("ipport,p", value<uint16_t>(), "server port");

but when I use unregistered options (yes, I have basic_command_line_parser::allow_unregistered()):

-calibration=something

I see:

the argument ('alibration=something') for option '-config' is invalid

My question after edition is: how to handle arguments working with getopt_long with boost::program_options?

like image 675
baziorek Avatar asked Dec 24 '14 11:12

baziorek


1 Answers

If you use boost::program_options, the symbol '=' is necessary to parse the parameters properly. It will throw an exception if it is missing. By the way, the boost::property_tree is also a very nice choice to parse config files. code:

#include <iostream>
#include <boost/propery_tree.hpp>
#include <boost/propery_tree/ini_parse.hpp>
int main()
{
    string filename("test.conf");
    boost::property_tree::ptree parser;
    boost::property_tree::ini_parser::read_ini(filename, parser);
    const string param_1 = parser.get<string>("DEFAULT.-server");
    const string param_2 = parser.get<string>("DEFAULT.-c");
    cout << param_1 << ' ' << param_2 << endl;
    return 0;
}

The "DEFAULT" is configure file's section name. You can try it.

like image 60
cwfighter Avatar answered Sep 18 '22 18:09

cwfighter