Linux之getopt

研究netmap代碼的時候,碰巧就瞭解了下關於配置參數的問題,促使我去研究的原因是每次安裝源代碼,需要自己

進行編譯鏈接都會用到./configure,當最後編譯鏈接完成後,若是要運行程序,少不了要在可執行程序後面添加參數,

其中有個最常見的就是 --help,不過這裏不講這個,將一個更簡單的  -h ,比如見得最多的 gcc -o 字段  ,那麼這個是怎麼

實現的呢?

函數getopt很好的解決了這個問題,可通過man手冊查看(man 3 getopt)直接看代碼:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc,char *argv[]){
    int ch; //用來存儲選項的ASSIC值
    while((ch = getopt(argc,argv,":hct:")) != -1){                  //":hct:"   的解釋可以查看manshouc,簡介第一個:表示給出了  -t  但是沒有參數時返回:
        printf("optind=%d\n",optind);           //該值是系統定義的變量,初始化值爲1,主要指向argv[]的字段,argv[0]爲程序名稱,從1開始
        printf("option = %c\n",ch);
        switch(ch){
            case 'h':                             //當可執行程序中有  -h  字段是打印幫助信息
                printf("Usage:%s [-h] [-c] [-t argument]\n",argv[0]);
                break;
            case 'c':                            //這個是測試
                printf("%c doesn't have an argument!\n",ch);
                break;
            case 't':
                printf("%c has an argument %s\n",ch,optarg);       //當可執行程序後出現   -t  時其後空格就是其參數,通過系統變量指針optarg獲取
                break;
            case '?':                          //當出現的選項不存在時返回?
                printf("the option didn't exsit!\n");
                printf("Usage:%s [-h] [-c] [-t argument]\n",argv[0]);
                break;
            case ':':                           //當出現的選項需要帶參數,而實際沒有給參數時,返回:    ,可以參考運行結果
                printf("option %s missing an argument!\n",argv[--optind]);
                printf("Usage:%s [-h] [-c] [-t argument]\n",argv[0]);
                optind++;
                break;
        }
    }
    return 0;
}


測試結果如下:

測試一:

[root@localhost tmp]# ./test -c -t test
optind=2
option = c
c doesn't have an argument!
optind=4
option = t
t has an argument test

測試二:

[root@localhost tmp]# ./test -t
optind=2
option = :
option -t missing an argument!
Usage:./test [-h] [-c] [-t argument]

測試三:

[root@localhost tmp]# ./test -l
optind=2
option = ?
the option didn't exsit!
Usage:./test [-h] [-c] [-t argument]

上述就是一個框架,可以根據需求進行添加,更進一步的像--help的實現方法下次有空再更新。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章