Technorati 标签: getopt_long

#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);

还是看下man里的解释:

The getopt_long() function works like getopt() except that it also accepts long options, started with two dashes.  (If the program accepts only long options, then
optstring should be specified as an empty string (""), not NULL.)  Long option names may be abbreviated if the abbreviation is unique or is  an  exact  match  for
some defined option.  A long option may take a parameter, of the form --arg=param or --arg param.

longopts is a pointer to the first element of an array of struct option declared in <getopt.h> as

     struct option {
         const char *name;
         int         has_arg;
         int        *flag;
         int         val;
     };

The meanings of the different fields are:

name   is the name of the long option.

has_arg
        is: no_argument (or 0) if the option does not take an argument; required_argument (or 1) if the option requires an argument; or optional_argument (or 2) if
        the option takes an optional argument.

flag   specifies how results are returned for a long option.  If flag is NULL, then getopt_long() returns val.  (For example, the calling program may set  val  to
        the  equivalent short option character.)  Otherwise, getopt_long() returns 0, and flag points to a variable which is set to val if the option is found, but
        left unchanged if the option is not found.

val    is the value to return, or to load into the variable pointed to by flag.

The last element of the array has to be filled with zeros.

If longindex is not NULL, it points to a variable which is set to the index of the long option relative to longopts.

getopt_long_only() is like getopt_long(), but '-' as well as "--" can indicate a long option.  If an option that starts with '-' (not "--") doesn't match  a  long
option, but does match a short option, it is parsed as a short option instead.

我来翻译下:

前面说的-h可以由getopt实现,那么—help则由getopt_long实现了。所谓的长选项即help,短选项就是h。

argc,argv,optstring都同前面。

name:如”help”,”version”等

has_arg:

[符号常量][数值][含义]

no_argument                0       该选项没有参数

required_argument     1       选项需要参数

optional_argument      2       选项参数可选

int *flag,int val:

flag和val相互依赖,主要分两种情况:

(1)、flag为NULL,val值用于确定该长选项,所以需要为长选项指定唯一的val值。这里也为长选项和短选项建立了桥梁。

(2)、flag不为NULL,则将val值存放到flag所指向的存储空间,用于标识该长选项出现过。

返回值:

程序中使用短选项,则返回短选项字符(如‘n'),当需要参数是,则在返回之前将参数存入到optarg中。

程序中使用长选项,返回值根据flag和val确定。当flag为NULL,则返回val值。所以根据val值做不同的处理,这也说明了val必须唯一。当val值等于短选项值,则可以使用短选项解析函数解析长选项;当flag不为NULL,则将val值存入flag所指向的存储空间,getopt_long返回0

出现未定义的长选项或者短选项,getopt_long返回?

解析完毕,getopt_long返回-1

 

copy参考里的一个例子,略微修改了下:

/*
 * =====================================================================================
 *       Filename:  getopt_long_l.c
 *    Description:  getopt_long() learn notes
 *
 *        Version:  1.0
 *        Created:  06/27/2012 08:25:20 PM
 *
 *         Author:  zhy (), [email protected]
 * =====================================================================================
 */

#include <stdio.h>
#include <getopt.h>

int main(int argc, char* argv[])
{
    int result, deb;
    struct option opts[] = {{"username", required_argument, NULL, 'n'},
                            {"version",  optional_argument, NULL, 'v'},
                            {"debug",    no_argument, &deb, 2},//flag!=NULL时,argument没有用?
                            {0,0,0,0}//why?
    };
    
    while ((result = getopt_long(argc, argv, "n:v::", opts, NULL))!=-1) {
        switch (result) {
            case 'n'://-n 或者--username
                printf("username is %s\n", optarg);
                break;
            case 'v'://-v 或者 --version
                printf("version is 1.0.0, %s\n", optarg);
                break;
            case 0://flag不为NULL
                printf("debug is %d\targs:%s\n", deb, optarg);
                break;
            case '?'://未定义的选项
                printf("?: %c %c\n", result, optopt);
                break;
            default:
                printf("default: %c\n", result);
                break;
        }
    }

    return 0;
}

getopt_long介绍_第1张图片

 

Q:

1.另外—version(即长选项)后不知道如何加可选参数?试了下修改程序后—debug –version后都是空格加参数的,参数用optarg读取。

getopt_long介绍_第2张图片

2.最后一个参数没看懂。参考里说是调试用。

参考:

http://www.cnitblog.com/zouzheng/archive/2007/04/02/25034.aspx

http://en.wikipedia.org/wiki/Getopt

http://blog.csdn.net/lanyan822/article/details/7692013

http://hi.baidu.com/agodliness/blog/item/554a2d516366711b367abeb2.html