getopt()简介
函數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 #include int main(int argc,char *argv[]) { int ch; opterr=0; while((ch=getopt(argc,argv,"a:b::cde"))!=-1) { printf("/n/n/n"); 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); } }
總結
以上是生活随笔為你收集整理的getopt()简介的全部內容,希望文章能夠幫你解決所遇到的問題。