getopt 函数 getopt_long函数

时间:2021-02-09 04:35:54

针对输入变量进行处理函数getopt,首先man大法:

 #include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;

可以看出,该函数主要用在慢函数中。

optarg——指向当前选项参数(如果有)的指针。
optind——再次调用 getopt() 时的下一个 argv 指针的索引。
optopt——最后一个已知选项

返回值:

If an option was successfully found, then getopt() returns the option character.  If all  command-line  options  have  been
       parsed,  then  getopt()  returns  -1.   If  getopt()  encounters an option character that was not in optstring, then '?' is
       returned.  If getopt() encounters an option with a missing argument, then the return value depends on the  first  character
       in optstring: if it is ':', then ':' is returned; otherwise '?' is returned.

简单解释如下:如果选项在字符串optstring中,则getopt返回该字符串,且字符串指针optarg指向对应的选项对应的值(如果是无参选项,则对应null);

                           继续查找下一个选项,如果要查找的选项不在字符串optstring中,则返回‘?’;

                           如果输入的各个选项均已在optstring查找一遍,则getopt返回-1。

所以一般对输入参数进行判定,在while中使用getopt进行判定。

如果选项需要带值,在后面跟‘:’, 例如‘a:b’  表示选项a需要带值且以空格隔开或者不用空格,而b不带值

‘::’ 表示必须带值,且必须不加空格  比如 ‘a::b:’  只能写为: -atext1  -b text2

程序示例:

#include     <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
int ch;
opterr = 0;
while( ( ch = getopt(argc,argv,"a:b:c:d::e") ) !=-1 )
{
switch(ch)
{
case 'a':
printf("a option: %s\n", optarg);
break;
case 'b':
printf("b option: %s\n", optarg);
break;
case 'c':
printf("c option: %s\n",optarg);
break;
case 'd':
printf("d option: %s\n",optarg);
break;
case 'e':
printf("e option: %s\n",optarg);
break;
case '?':
printf("illegal option:%c\n",ch);
break;
}

}

}

wln@iZ232ngsvp8Z:~/2015/11> ./getopt4 -a 1 -b 2 -c 3 -d4 -e 5 -w 6
a option: 1
b option: 2
c option: 3
d option: 4
e option: (null)
illegal option:?


程序示例2:

wln@iZ232ngsvp8Z:~/2015/11> cat getopt4.c
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
int ch;
opterr = 0;
while( ( ch = getopt(argc,argv,"a:b:c:d::e") ) !=-1 )
{
switch(ch)
{
case 'a':
printf("a option: %s %s\n", optarg,argv[optind]);
break;
case 'b':
printf("b option: %s\n", optarg);
break;
case 'c':
printf("c option: %s\n",optarg);
break;
case 'd':
printf("d option: %s\n",optarg);
break;
case 'e':
printf("e option: %s\n",optarg);
break;
case '?':
printf("illegal option:%c\n",ch);
break;
}

}

int i=0;
while(i++<argc)
printf("%d\t%s\n",i,argv[i]);
if (optind < argc)
printf("non-option ARGV-elements: \n");
while (optind < argc)
printf("%s\n", argv[optind++]);

}

wln@iZ232ngsvp8Z:~/2015/11> ./getopt4  -a 1 -b -c -d -e 1 2 3
a option: 1 -b
b option: -c
d option: (null)
e option: (null)
1       -a
2       1
3       -b
4       -c
5       -d
6       -e
7       1
8       2
9       3
10      (null)
non-option ARGV-elements:
1
2

3

--------------

optind : option index

while (optind < argc)
        printf("%s\n", argv[optind++]);

:: getopt解析了它能识别的参数,剩余的在此,从上面程序结果也可以看出


函数getopt_long

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 exam-
ple, 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


程序(来自linux man getopt)

#include <stdio.h>     /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>

int
main(int argc, char **argv)
{
int c;
int digit_optind = 0;

while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"verbose", 0, 0, 0},
{"create", 1, 0, 'c'},
{"file", 1, 0, 0},
{0, 0, 0, 0}
};

c = getopt_long(argc, argv, "abc:d:012",
long_options, &option_index);
if (c == -1)
break;

switch (c) {
case 0:
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;

case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;

case 'b':
printf("option b\n");
break;

case 'c':
printf("option c with value '%s'\n", optarg);
break;

case 'd':
printf("option d with value '%s'\n", optarg);
break;

case '?':
break;

default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}

if (optind < argc) {
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}

exit(EXIT_SUCCESS);
}

test:

wln@iZ232ngsvp8Z:~/2015/11> ./getopt2 --add ADD --append --delete DELETE --verbose --create CREATE --file FILE  -c fae
option add with arg ADD
option append
option delete with arg DELETE
option verbose
option c with value 'CREATE'
option file with arg FILE
option c with value 'fae'


推荐阅读:

1.http://www.cnblogs.com/caosiyang/archive/2012/03/26/2417689.html