#include <getopt.h>
int getopt (int ___argc, char *const *___argv, const char *__shortopts);
int getopt_long (int ___argc, char *const *___argv, const char *__shortopts,const struct option *__longopts, int *__longind);
#include <iostream> #include <getopt.h> int main(int argc,char** argv){ char* const short_options="nbl:"; int ret=0; while(-1!=(ret=getopt(argc,argv,short_options))){ std::cout<<(char)ret; if(optarg) std::cout<<"="<<optarg; std::cout<<std::endl; } std::cout<<ret<<std::endl; return 0; }
#include <stdio.h> #include <getopt.h> char *l_opt_arg; char* const short_options = "nbl:"; //You should guarantee val equals its shot_option ,or switch case may work not as excepted struct option long_options[] = { { "name", 0, NULL, 'n' }, { "bf_name", 1, NULL, 'b' }, { "love", 1, NULL, 'l' }, { 0, 0, 0, 0}, }; int main(int argc, char *argv[]) { int c; int index=0; while((c = getopt_long (argc, argv, short_options, long_options, &index)) != -1) { switch (c) { case 'n': printf("My name is XL.index=%d\n",index); break; case 'b': printf("His name is ST.index=%d\n",index); break; case 'l': l_opt_arg = optarg; printf("Our love is %s!index=%d\n", l_opt_arg,index); break; default: printf("I am enock:c=%c,index=%\n",c,index); } } return 0; }
optind
——再次调用 getopt()/getopt_long()
时的下一个 argvs元素的 索引,注意getopt和getopt_long会调整argvs中命令行参数的位置,对符合参数格式的调整到前面,不符合参数格式的调整到后面,但相对顺序不变,如下在上面代码中的while(getopt_long)后面添加打印argvs的代码,
std::cout<<"optind="<<optind<<std::endl; std::cout<<"argvs after getopt_long"<<std::endl; for(int i=0;i<argc;++i){ std::cout<<argv[i]<<std::endl; }
Our love is lval!index=0
optind=3
argvs after getopt_long
./a.out
-l
lval
file1.in
file2.in
经过getopt_long后argvs元素的顺序变了。