, . , ++, , "getopt". getopt_long(), (, -c), (, --input). getopt_long_only(), . . .
, , :
#include <iostream>
#include <getopt.h>
#include <map>
#include <string>
int main (int argc, char** argv)
{
std::map<std::string, std::string> input_parameters ;
input_parameters["input"] = "default_in" ;
input_parameters["output"] = "default_out" ;
const struct option longopts[] =
{
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{0,0,0,0}
};
int c(0);
while (c != -1) {
int option_index(-1) ;
c = getopt_long(argc, argv, "i:o:", longopts, &option_index) ;
if ((c>0)&&(option_index>=0)) {
std::cout << option_index << std::endl;
input_parameters[longopts[option_index].name] = optarg ;
}
switch (c) {
case 'i':
input_parameters["input"] = optarg ;
case 'o':
input_parameters["output"] = optarg ;
case '?':
break ;
}
}
std::cout << "input = " << input_parameters["input"] << std::endl;
std::cout << "output = " << input_parameters["output"] << std::endl;
return 0 ;
}
, , , . :
$ ./myscript --input inputfile.txt --output outputfile.txt
input = inputfile.txt
output = outputfile.txt
$ ./myscript -i inputfile.txt -o outpufile.txt
input = inputfile.txt
output = outputfile.txt
--input -i ( --output -o).
( CLOptions , getopt)
, getopt , , , int . ! , "CLOptions", #include "CLOptions.h" ( ), . -h -help ! bool, double, int string , . GitHub how could the above method be implemented . Note that the class is C ++ 11 and will require -std=c++11at compile time (although if someone asks, I can try to create version C code).
Although I have not tried them yet, there are also many other command line programs that were developed by other people to solve this problem (e.g. options or dropt ). You can probably find them by clicking on the link.