? ? ? ?
簡(jiǎn)書著作權(quán)歸作者所有葡兑,任何形式的轉(zhuǎn)載都請(qǐng)聯(lián)系作者獲得授權(quán)并注明出處毫痕。
可以解析短參數(shù),所謂短參數(shù)就是指選項(xiàng)前只有一個(gè)“-”的情況。
getopt函數(shù)
#include<unistd.h>
int getopt(int argc,char * const argv[],const char *optstring);
extern char *optarg; //當(dāng)前選項(xiàng)參數(shù)字串
extern int optind; //argv的當(dāng)前索引值(下文會(huì)詳細(xì)介紹)
各參數(shù)的意義:
argc: 通常為main函數(shù)中的argc
argv: 通常為main函數(shù)中的argv
optstring: 用來(lái)指定選項(xiàng)的內(nèi)容(如:"ab:c")知允,它由多個(gè)部分組成,表示的意義分別為:
- 單個(gè)字符狞膘,表示選項(xiàng)研乒。
- 單個(gè)字符后接一個(gè)冒號(hào):表示該選項(xiàng)后必須跟一個(gè)參數(shù)。參數(shù)緊跟在選項(xiàng)后或者以空格隔開佳窑。該參數(shù)的指針賦給optarg制恍。
- 單個(gè)字符后跟兩個(gè)冒號(hào),表示該選項(xiàng)后可以跟一個(gè)參數(shù)华嘹,也可以不跟吧趣。如果跟一個(gè)參數(shù),參數(shù)必須緊跟在選項(xiàng)后不能以空格隔開耙厚。該參數(shù)的指針賦給optarg强挫。
調(diào)用該函數(shù)將返回解析到的當(dāng)前選項(xiàng),該選項(xiàng)的參數(shù)將賦給optarg薛躬,如果該選項(xiàng)沒有參數(shù)俯渤,則optarg為NULL。
一型宝、getopt 函數(shù)的一般使用
新建文件 test.c八匠,并在文件中輸入以下內(nèi)容:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[]) {
int opt = 0;
while ((opt = getopt(argc, argv, "ab:c::")) != -1) {
switch (opt) {
case 'a':
printf("option a: %s\n", optarg); // 在這里 optarg == NULL 是成立的
break;
case 'b':
printf("option b: %s\n", optarg);
break;
case 'c':
printf("option c: %s\n", optarg);
break;
}
}
return 0;
}
執(zhí)行如下命令進(jìn)行編譯:
gcc test.c -o test
運(yùn)行命令及得到相應(yīng)結(jié)果如下:
命令1
./test -a -b 123
結(jié)果1
option a: (null)
option b: 123
命令2
./test -a -b 123 -c
結(jié)果2
option a: (null)
option b: 123
option c: (null)
命令3
./test -a -b 123 -cbubble
結(jié)果3
option a: (null)
option b: 123
option c: bubble
二、注意點(diǎn)
1趴酣、getopt 函數(shù)解析完命令行中的最后一個(gè)參數(shù)后梨树,argv 中的參數(shù)順序?qū)?huì)發(fā)生改變——執(zhí)行的文件名仍然排在最前面,接下來(lái)的部分是選項(xiàng)及其參數(shù)岖寞,最后是其他參數(shù)抡四。如執(zhí)行的命令為
./test -a value -b 123 key -cbubble
輸出結(jié)果仍然為
option a: (null)
option b: 123
option c: bubble
如果沒有使用 getopt 函數(shù)解析命令行參數(shù)的話,argv 中的內(nèi)容應(yīng)該如下仗谆,
argv[0] = "./test"
argv[1] = "-a"
argv[2] = "value"
argv[3] = "-b"
argv[4] = "123"
argv[5] = "key"
argv[6] = "-cbubble"
然而指巡,由于這里受到了 getopt 函數(shù)的影響,argv 中的實(shí)際內(nèi)容如下隶垮,
argv[0] = "./test"
argv[1] = "-a"
argv[2] = "-b"
argv[3] = "123"
argv[4] = "-cbubble"
argv[5] = "value"
argv[6] = "key"
2藻雪、上面提到的 while 循環(huán)在結(jié)束后,除了 argv 中的參數(shù)位置會(huì)發(fā)生變化外狸吞,還會(huì)將 optind 變量指向第一個(gè)不是選項(xiàng)也不是選項(xiàng)參數(shù)的參數(shù)勉耀,如對(duì)于上述提到的參數(shù)位置發(fā)生變化的 argv指煎,optind 指向 "value" 的位置。