程序會根據讀取的參數執行相應的操作,在C語言中,這個功能一般是靠getopt()這個函數,結合switch語句來完成的,首先來看下面的代碼:
#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編譯後,在終端行執行以上的命令:
則會有如下的輸出:
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+
main(int argc,char *argv[])中的argc是一個整型,argv是一個指針數組,argc記錄argv的大小。上面的例子中。
argc=5;
argv[0]=./a.out
argv[1]=-a1234
argv[2]=-b432
argv[3]=-c
argv[4]=-d
getopt()函數的原型爲getopt(int argc,char *const argv[],const char *optstring)。
其中argc和argv一般就將main函數的那兩個參數原樣傳入。
optstring是一段自己規定的選項串,例如本例中的"a:b::cde",表示可以有,-a,-b,-c,-d,-e這幾個參數。
“:”表示必須該選項帶有額外的參數,全域變量optarg會指向此額外參數,“::”標識該額外的參數可選(有些Uinx可能不支持“::”)。
全域變量optind指示下一個要讀取的參數在argv中的位置。
如果getopt()找不到符合的參數則會印出錯信息,並將全域變量optopt設爲“?”字符。
如果不希望getopt()印出錯信息,則只要將全域變量opterr設爲0即可。
本文出自 51CTO.COM技術博客