getopt()用来分析命令行参数。
头文件 #include<unistd.h>
定义函数 int getopt(int argc,char * const argv[ ],const char * optstring);
extern char *optarg;
extern int optind, opterr, optopt;
optind是下一次进行选项搜索的开始索引,下一次从argv[optind]开始索引。
opterr
先分析一段代码:
1 #include <stdio.h>
2 #include "apue.h"
3
4 int main(int argc,char **argv)
5 {
6 int oc;
7 while((oc = getopt(argc,argv,":n::gl:"))!=-1)
8 {
9 switch(oc)
10 {
11 case 'n':
12 printf("option n\n");
13 if(optarg)
14 {
15 printf("%s\n",optarg);
16 }
17 else
18 {
19 printf("no argument\n");
20 }
21 break;
22 case 'g':
23 printf("option g\n");
24 break;
25 case 'l':
26 printf("option l\n");
27 printf("%s\n",optarg);
28 break;
29 case '?':
30 putchar(oc);
31 printf("无效选项\n");
32 break;
33 case ':':
34 putchar(oc);
35 printf("缺少选项的参数\n");
36 break;
37 }
38 }
39 return 0;
40 }
运行结果:
./a.out -g
option g
./a.out -h
?无效选项
./a.out -l
:缺少选项的参数
./a.out -l hello
option l
hello
./a.out -lhello
option l
hello
./a.out -n
option n
no argument
./a.out -n hello
option n
no argument
./a.out -nhello
option n
hello
分析:
ngl是选项,如果是无效选项,返回‘?’,如果缺少选项的参数,返回‘:’(如果ngl前面的那个冒号去掉的话,缺少选项参数也返回‘?’)。
::表示参数可有可无,从运行结果看,-nhello,参数和选项之间没有空格才能解析出来。
1 #include <stdio.h>
2 #include "apue.h"
3
4 int main(int argc,char **argv)
5 {
6 int oc;
7 printf("optind:%d\n",optind);
8 while((oc = getopt(argc,argv,":n::gl:"))!=-1)
9 {
10 printf("optind:%d\n",optind);
11 switch(oc)
12 {
13 case 'n':
14 printf("option n\n");
15 if(optarg)
16 {
17 printf("%s\n",optarg);
18 }
19 else
20 {
21 printf("no argument\n");
22 }
23 break;
24 case 'g':
25 printf("option g\n");
26 break;
27 case 'l':
28 printf("option l\n");
29 printf("%s\n",optarg);
30 break;
31 case '?':
32 putchar(oc);
33 printf("无效选项\n");
34 break;
35 case ':':
36 putchar(oc);
37 printf("缺少选项的参数\n");
38 break;
39 }
41 printf("optind:%d\n",optind);
42 return 0;
43 }
44
运行:
./a.out -l 1 2 3 4
optind:1
optind:3
option l
1
optind:3
可以看出:optind会指向下一个开始扫描的位置,开始的时候的等于1,也就是从-l开始扫描,-l是有参数的,所以下一次从3开始扫描,因为没有扫描到有效选项,返回-1,跳出循环之后optind仍为3。