c语言的可变参数设计2方面问题,其1是类似于printf函数的va_list类型(放在下一个章节讲述),其2是getopt函数的应用问题-即本章讲述的问题
在开始本章之前,先解释几个小的参数
1.optarg
2.optind
3.opterr
4.optopt
具体的例子如下面的函数所示
1 #include <unistd.h> 2 #include <stdio.h> 3 int main(int argc, char * argv[]) 4 { 5 6 int ch; 7 printf("\n\n"); 8 printf("the initial value of optind:%d, and opterr: %d\n",optind,opterr); //2.用来记录下一个检索位置,3.是否将错误信息输出到stderr 9 printf("--------------------------\n"); 10 11 while ((ch = getopt(argc, argv, "ab:c:de::")) != -1) 12 { 13 printf("optind: %d\n", optind); 14 switch (ch) 15 { 16 case 'a': 17 printf("HAVE option: -a\n\n"); 18 break; 19 case 'b': 20 printf("HAVE option: -b\n"); 21 printf("The argument of -b is %s\n\n", optarg); //1.用来保存选项的参数 22 break; 23 case 'c': 24 printf("HAVE option: -c\n"); 25 printf("The argument of -c is %s\n\n", optarg); 26 break; 27 case 'd': 28 printf("HAVE option: -d\n"); 29 break; 30 case 'e': 31 printf("HAVE option: -e\n"); 32 printf("The argument of -e is %s\n\n", optarg); 33 break; 34 case '?': 35 printf("Unknown option: %c\n",(char)optopt); //4.不在字符串optstring中的选项 36 break; 37 } 38 } 39 40 41 }
gcc xxx.c 后
./a.out -b "xixi_haha" 则
optind:1,opterr:1 // 1.
--------------------------
optind: 3 // 2.
HAVE option: -b // 3.
The argument of -b is xixi_haha // 4.
// 1. argc表示参数的个数,argv[]表示每个参数字符串,对于上面的输出argc就为3,argv[]分别为: ./main 和 -b 和"xixi_haha"
// 1. 实际上真正的参数是用第二个-b 开始,也就是argv[1],所以optind的初始值为1
// 2. 当执行getopt()函数时,会依次扫描每一个命令行参数(从下标1开始),第一个-b,是一个选项,而且这个选项在选项字符串optstring中有,
// 2. 我们看到b后面有冒号,也就是b后面必须带有参数,而"xixi_haha"就是他的参数。所以这个命令行是符合要求的
// 3. 至于执行后optind为什么是3,这是因为optind是下一次进行选项搜索的开始索引,也是说下一次getopt()函数要从argv[3]开始搜索。
// 3. 当然,这个例子argv[3]已经没有了,此时getopt()函数就会返回-1。
// 4.