命令行程序选项解析函数—getopt_long

来源:互联网 发布:linux系统装在哪个分区 编辑:程序博客网 时间:2024/04/30 04:56

转载请注明出处:http://blog.csdn.net/zhangyang0402/archive/2010/06/15/5671554.aspx

 

getopt函数只能解析短选项,getopt_long除了接受短选项,还能解析长选项。因此,getopt_long函数在linux命令行程序中使用得最广泛。

 

 1. 函数原型    

  #include <getopt.h>

 int getopt_long(int argc,  char * const argv[], const char *optstring, const struct option *longopts, int *longindex);

 

2. 参数

(1)argc

(2)argv

(3)optstring:短选项字符集合。若只有长选项,则置为空字符串(“”)

(4)longopts:指向struct option数组的第一个元素,结构体option定义如下

struct option

{

  const char *name;  //长选项名称

  int has_arg; //是否有参数no_argument(0)  required_argument(1)  optional_argument(2)

  int *flag; //指定长选项的返回结果:NULL 返回val;非空返回0

  int val; //返回的值或装载flag指向的变量

};

注:struct option 数组最后一个元素用0填充

(5)longindex 非空的话,指向长选项的索引

 

3. 返回值

对短选项,返回对应的选项字符;

对长选项,若flagNULL,返回val;否则返回0

 

4. 测试

这里只测试长选项,至于短选项的处理则和getopt函数相同

mygetoptlong.c

 

 

执行结果:

$ ./mygetoptlong --input infile --all --output outfile --version --help file

option "input": infile

 

option "all":

 

option "output": outfile

 

option "version":

 

option "help":

 

Usage: ./mygetoptlong [--input infile] [--all] [--output outfile] [--version] [--help] [file]

 

 

non-opotion arguments below:

file

原创粉丝点击