一、上代码
#include <stdio.h>
#include <unistd.h>
int main(int argc, char * argv[])
{
int ch;
printf("\n\n");
printf("optind:%d,opterr:%d\n",optind,opterr);
printf("--------------------------\n");
while ((ch = getopt(argc, argv, "ab:c:de::")) != -1)
{
printf("optind: %d\n", optind);
switch (ch)
{
case 'a':
printf("HAVE option: -a\n\n");
printf("The argument of -a is %s\n\n", optarg);
break;
case 'b':
printf("HAVE option: -b\n");
printf("The argument of -b is %s\n\n", optarg);
break;
case 'c':
printf("HAVE option: -c\n");
printf("The argument of -c is %s\n\n", optarg);
break;
case 'd':
printf("HAVE option: -d\n");
printf("The argument of -d is %s\n\n", optarg);
break;
case 'e':
printf("HAVE option: -e\n");
printf("The argument of -e is %s\n\n", optarg);
break;
case '?':
printf("Unknown option: %c\n",(char)optopt);
break;
}
}
}
二、 解析
"ab:c:de::"这个字符串,表示程序接收5个参数,-a,-b,-c,-d,-e。其中a和d后面没接任何冒号,说明这个选项不接收参数,b和c后面一个冒号,说明必须接受参数,可以有空格也可以没有空格,比如-b 123和-b123都行。最后是e选项有两个冒号,说明它是可选参数,可以接收参数也可以不接收参数,最为灵活,但是如果有参数的时必须是无空格,比如-e123。
optind是全局变量保存下次检索位置,比如option=3,表示下次从argv[3]又开始解析,optarg是全局变量保存选项对应的参数,opterr是全局变量表明是否输出到stdout。
三、测试
1. ./toption -a -b iamb -c iamc -d -eiame-witout-space
optind:1,opterr:1
--------------------------
optind: 2
HAVE option: -a
The argument of -a is (null)
optind: 4
HAVE option: -b
The argument of -b is iamb
optind: 6
HAVE option: -c
The argument of -c is iamc
optind: 7
HAVE option: -d
The argument of -d is (null)
optind: 8
HAVE option: -e
The argument of -e is iame-witout-space
2. ./toption -abLAJI iamb -c iamc -d -eiame-witout-space
optind:1,opterr:1
--------------------------
optind: 1
HAVE option: -a
The argument of -a is (null)
optind: 2
HAVE option: -b
The argument of -b is LAJI
optind: 5
HAVE option: -c
The argument of -c is iamc
optind: 6
HAVE option: -d
The argument of -d is (null)
optind: 7
HAVE option: -e
The argument of -e is iame-witout-space