标签:
argc)、指向这些参数的数组 (argv) 和选项字串 (optstring)
后,getopt() 将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有可识别的选项,将返回-1,此任务就完成了。getopt() 所设置的全局变量包括:char *optarg——当前选项参数字串(如果有)。int optind——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。int optopt——当发现无效选项字符之时,getopt()函数或返回‘?‘字符,或返回‘:‘字符,并且optopt包含了所发现的无效选项字符。#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int ch;
opterr=0;
while((ch=getopt(argc,argv,"a:b::cde"))!=-1)
{
printf("optind:%d\n",optind);
printf("optarg:%s\n",optarg);
printf("ch:%c\n",ch);
switch(ch)
{
case 'a':
printf("option a:'%s'\n",optarg);
break;
case 'b':
printf("option b:'%s'\n",optarg);
break;
case 'c':
printf("option c\n");
break;
case 'd':
printf("option d\n");
break;
case 'e':
printf("option e\n");
break;
default:
printf("other option:%c\n",ch);
}
printf("optopt+%c\n",optopt);
}
} 用gcc编译后,在终端行执行以上的命令: ./a.out -a1234 -b432 -c -d 则会有如下的输出: optind:2 optarg:1234 ch:a option a:'1234' optopt+ optind:3 optarg:432 ch:b option b:'432' optopt+ optind:4 optarg:(null) ch:c option c optopt+ optind:5 optarg:(null) ch:d option d optopt+
标签:
原文地址:http://blog.csdn.net/chun_1959/article/details/45027707