命令行提取参数
getopt_long函数,能够在Linux命令行提取短选项(-开头,与选参数之间隔空)与长选项(–开头连接参数)。它的原型是这样的。
#include <unistd.h>
#include <getopt.h>
int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);
如果只想要提取长选项,那么就需要把optstring指针设为NULL。如果也需要用到短选项,那么这里设置为标识的字符。
option结构体的原型为
struct option {
const char *name;//长选项的选项名。
int has_arg;//0:不需要参数,1:需要参数,2:参数是可选的
int *flag;//指定如何为长选项返回结果。如果flag是null,那么getopt_long返回val(可以将val设置为等效的短选项字符),否则getopt_long返回0.
int val;//返回值,参考flag
};
那么使用的时候,我们势必要判断命令行传入各个参数是否符合我们的要求,再进行筛选提取。
while( -1 != (optvar=getopt_long