Command line arguments
Parsing command-line arguments. More...
Parsing command-line arguments.
If you would like to pass command line arguments to your Player client programs you can use the getopt feature provided by unistd.h.
#include <unistd.h>
You must supply a series of characters in optflags, which are the legitimate options to you program. If the characher is followed by a colon (:) then that option requires an additional parameter. These parameters are returned as const char* so you must use functions like atoi() or atof() if you would like numerical results.
int parse_args(int argc, char** argv)
{
// set the flags
const char* optflags = "h:p:i:d:u:lm:";
int ch;
// use getopt to parse the flags
while(-1 != (ch = getopt(argc, argv, optflags)))
{
switch(ch)
{
// case values must match long_options
case 'h': // hostname
gHostname = optarg;
break;
case 'p': // port
gPort = atoi(optarg);
break;
case 'i': // index
gIndex = atoi(optarg);
break;
case 'd': // debug
gDebug = atoi(optarg);
break;
case 'u': // update rate
gFrequency = atoi(optarg);
break;
case 'm': // datamode
gDataMode = atoi(optarg);
break;
case 'l': // datamode
gUseLaser = true;
break;
case '?': // help
case ':':
default: // unknown
print_usage(argc, argv);
exit (-1);
}
}
return (0);
} // end parse_args
It is also often helpfull to include a short output function that explains the option parameters to your program.
USAGE: myprogram [options] Where [options] can be: -h <hostname> : hostname to connect to (default: localhost) -p <port> : port where Player will listen (default: 6665) -i <index> : device index (default: 0) -d <level> : debug message level (0 = none -- 9 = all) -u <rate> : set server update rate to <rate> in Hz -m <datamode> : set server data delivery mode PLAYER_DATAMODE_PUSH = 1 PLAYER_DATAMODE_PULL = 2
void print_usage(int argc, char** argv)
{
using namespace std;
cerr << "USAGE: " << *argv << " [options]" << endl << endl;
cerr << "Where [options] can be:" << endl;
cerr << " -h <hostname> : hostname to connect to (default: "
<< PlayerCc::PLAYER_HOSTNAME << ")" << endl;
cerr << " -p <port> : port where Player will listen (default: "
<< PlayerCc::PLAYER_PORTNUM << ")" << endl;
cerr << " -i <index> : device index (default: 0)"
<< endl;
cerr << " -d <level> : debug message level (0 = none -- 9 = all)"
<< endl;
cerr << " -u <rate> : set server update rate to <rate> in Hz"
<< endl;
cerr << " -l : Use laser if applicable"
<< endl;
cerr << " -m <datamode> : set server data delivery mode"
<< endl;
cerr << " PLAYER_DATAMODE_PUSH = "
<< PLAYER_DATAMODE_PUSH << endl;
cerr << " PLAYER_DATAMODE_PULL = "
<< PLAYER_DATAMODE_PULL << endl;
} // end print_usage
For the complete code see examples/libplayerc++/args.h