getopt()简介
函數(shù)getopt()用來分析命令行參數(shù),其函數(shù)原型和相關(guān)變量聲明如下:
#include
extern char *optarg;
extern int optind,? // 初始化值為1,下一次調(diào)用getopt時,從optind存儲的位置重新開始檢查選項,也就是從下一個'-'的選項開始。
extern int opterr,? // 初始化值為1,當(dāng)opterr=0時,getopt不向stderr輸出錯誤信息。
extern int optopt;? // 當(dāng)命令行選項字符不包括在optstring中或者選項缺少必要的參數(shù)時,該選項存儲在optopt中,getopt返回’?’。
int getopt(int argc, char * const argv[], const char *optstring);
optarg和optind是兩個最重要的external?????????????????????????????????????????????????????????????????????????????????????????????
變量。optarg是指向參數(shù)的指針(當(dāng)然這只針對有參數(shù)的選項);optind是argv[]數(shù)組的索引,眾所周知,argv[0]是函數(shù)名稱,所有參數(shù)從argv[1]
開始,所以optind被初始化設(shè)置指為1。 每調(diào)用一次getopt()函數(shù),返回一個選項,如果該選項有參數(shù),則optarg指向該參數(shù)。?????????????????
在命令行選項參數(shù)再也檢查不到optstring中包含的選項時,返回-1。
函數(shù)getopt()有三個參數(shù),argc和argv[]應(yīng)該不需要多說,下面說一下字符串optstring,它是作為選項的字符串的列表。
函數(shù)getopt()認為optstring中,以'-????????????????????????????????????????????????????????????????????????????????????????????????
’開頭的字符(注意!不是字符串!!)就是命令行參數(shù)選項,有的參數(shù)選項后面可以跟參數(shù)值。optstring中的格式規(guī)范如下:
1) 單個字符,表示選項,
2) 單個字符后接一個冒號”:”,表示該選項后必須跟一個參數(shù)值。參數(shù)緊跟在選項后或者以空格隔開。該參數(shù)的指針賦給optarg。
3) 單個字符后跟兩個冒號”:”,表示該選項后必須跟一個參數(shù)。???????????????????????????????????????????????????????????????????????
參數(shù)必須緊跟在選項后不能以空格隔開。該參數(shù)的指針賦給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); } }
總結(jié)
以上是生活随笔為你收集整理的getopt()简介的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。