關(guān)于 C 語(yǔ)言中使用庫(kù)函數(shù) getopt 解析命令行參數(shù)的使用方法

? ? ? ?
簡(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è)部分組成,表示的意義分別為:

  1. 單個(gè)字符,表示選項(xiàng)。
  2. 單個(gè)字符后接一個(gè)冒號(hào):表示該選項(xiàng)后必須跟一個(gè)參數(shù)。參數(shù)緊跟在選項(xiàng)后或者以空格隔開(kāi)。該參數(shù)的指針賦給optarg。
  3. 單個(gè)字符后跟兩個(gè)冒號(hào),表示該選項(xiàng)后可以跟一個(gè)參數(shù),也可以不跟。如果跟一個(gè)參數(shù),參數(shù)必須緊跟在選項(xiàng)后不能以空格隔開(kāi)。該參數(shù)的指針賦給optarg。

調(diào)用該函數(shù)將返回解析到的當(dāng)前選項(xiàng),該選項(xiàng)的參數(shù)將賦給optarg,如果該選項(xiàng)沒(méi)有參數(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

如果沒(méi)有使用 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" 的位置。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容