getopt_long原型
#define no_argument 0 #define required_argument 1 #define optional_argument 2 struct option { const char *name; //名称,下面实例中使用的--help,--version int has_arg; //是否有参数,可选0,1,2三个值,就是上面的那三个宏定义 int *flag; //返回值,传入的一个int指针,表示该参数的解析结果,如果是NULL,那么返回值就会被写到getopt_long的返回值中。 int val; //name的简写 }; #include <unistd.h> int getopt(int argc, char * const argv[],const char *optstring); extern char *optarg; extern int optind, opterr, optopt; #include <getopt.h> int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex); int getopt_long_only(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
optstring就是下面程序中的:"hva:b:",就是那一群简写集合,后面带冒号意思(比如-a)就是这个-a后面要加参数。
getopt_long实例
经常为了写小程序的解析参数感觉麻烦,所以就写一个小函数模板以后复制用。
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int discovery_options(int argc, char** argv, bool& show_help, bool& show_version,string& input) { int ret = 0; static option long_options[] = { {"help", no_argument, &ret, ‘h‘}, {"version", no_argument, 0, ‘v‘}, {"arga", required_argument , 0, ‘a‘}, {"argb", required_argument , 0, ‘b‘}, {0, 0, 0, 0} }; int opt = 0; int option_index = 0; while((opt = getopt_long(argc, argv, "hva:b:", long_options, &option_index)) != -1){ switch(opt){ case ‘h‘: show_help = true; break; case ‘v‘: show_version = true; break; case ‘a‘: input = optarg; break; case ‘b‘: input = optarg; break; default: show_help = true; break; } } // check values return ret; } void help(char** argv){ printf("%s, Copyright (c) 2013-2015 BuguTian\n", argv[0]); printf("" "Usage: %s <Options> <-a REQUEST>\n" "-h no arg,mean help\n" "-v no arg,mean version\n" "-a arga\n" "-b argb\n", argv[0]); exit(0); } void version() { printf("V1.1.1\n"); exit(0); } int main(int argc, char** argv){ int ret = 0; bool show_help = false; bool show_version = false; string input=""; if((ret = discovery_options(argc, argv, show_help, show_version, input))){ printf("discovery options failed. ret=%d", ret); return ret; } if(show_help){ help(argv); } if(show_version){ version(); } printf("running...\n"); return 0; }
时间: 2024-10-10 10:35:02