函数说明 getopt()用来分析命令行参数。参数argc和argv分别代表参数个数和内容,跟main()函数的命令行参数是一样的。参数 optstring为选项字符串, 告知 getopt()可以处理哪个选项以及哪个选项需要参数,如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果在处理期间遇到了不符合optstring指定的其他选项getopt()将显示一个错误消息,并将全域变量optopt设为“?”字符,如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
该函数是读wpa_supplicant源码的main函数里面得到的一个例子,觉得用起来挺好玩的。
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int ch;
opterr = 0;
for (;;)
{
ch = getopt(argc, argv,
"a:bc:C:D:de:f:g:G:hi:I:KLMm:No:O:p:P:qsTtuvW");
if (ch < 0)
break;
switch(ch)
{
case 'a':
printf("option a:’%s’\n",optarg);
break;
case 'b':
printf("option b :b\n");
break;
default:
printf("other option :%c\n",ch);
}
printf("optopt +%c\n",optopt);
}
return 0;
}