函數getopt()用來分析命令列參數,其函數原型和相關變數聲明如下:
#include
extern char *optarg;
extern int optind, // 初始化值為1,下一次調用getopt時,從optind儲存的位置重新開始檢查選項,也就是從下一個'-'的選項開始。
extern int opterr, // 初始化值為1,當opterr=0時,getopt不向stderr輸出錯誤資訊。
extern int optopt; // 當命令列選項字元不包括在optstring中或者選項缺少必要的參數時,該選項儲存在optopt中,getopt返回’?’。
int getopt(int argc, char * const argv[], const char *optstring);
optarg和optind是兩個最重要的external
變數。optarg是指向參數的指標(當然這隻針對有參數的選項);optind是argv[]數組的索引,眾所周知,argv[0]是函數名稱,所有參數從argv[1]
開始,所以optind被初始化設定指為1。 每調用一次getopt()函數,返回一個選項,如果該選項有參數,則optarg指向該參數。
在命令列選項參數再也檢查不到optstring中包含的選項時,返回-1。
函數getopt()有三個參數,argc和argv[]應該不需要多說,下面說一下字串optstring,它是作為選項的字串的列表。
函數getopt()認為optstring中,以'-
’開頭的字元(注意!不是字串!!)就是命令列參數選項,有的參數選項後面可以跟參數值。optstring中的格式規範如下:
1) 單個字元,表示選項,
2) 單個字元後接一個冒號”:”,表示該選項後必須跟一個參數值。參數緊跟在選項後或者以空格隔開。該參數的指標賦給optarg。
3) 單個字元後跟兩個冒號”:”,表示該選項後必須跟一個參數。
參數必須緊跟在選項後不能以空格隔開。該參數的指標賦給optarg。(這個特性是GNU的擴充)。
#include<br />#include </p><p>int main(int argc,char *argv[])<br />{<br /> int ch;<br /> opterr=0; </p><p> while((ch=getopt(argc,argv,"a:b::cde"))!=-1)<br /> {<br /> printf("/n/n/n");<br /> printf("optind:%d/n",optind);<br /> printf("optarg:%s/n",optarg);<br /> printf("ch:%c/n",ch);<br /> switch(ch)<br /> {<br /> case 'a':<br /> printf("option a:'%s'/n",optarg);<br /> break;<br /> case 'b':<br /> printf("option b:'%s'/n",optarg);<br /> break;<br /> case 'c':<br /> printf("option c/n");<br /> break;<br /> case 'd':<br /> printf("option d/n");<br /> break;<br /> case 'e':<br /> printf("option e/n");<br /> break;<br /> default:</p><p> printf("other option:%c/n",ch);<br /> }<br /> printf("optopt+%c/n",optopt);<br /> }<br />}<br />