C語言 getopt()函數的使用

getopt(分析命令行參數)   

相關函數表頭文件
        #include<unistd.h>
定義函數
        int getopt(int argc,char * const argv[ ],const char * optstring);
函數說明
        getopt()用來分析命令行參數。參數argc和argv是由main()傳遞的參數個數和內容。參數optstring 則代表欲處理的選項字符串。此函數會返回在argv 中下一個的選項字母,此字母會對應參數optstring 中的字母。如果選項字符串裏的字母后接着冒號“:”,則表示還有相關的參數,全域變量optarg 即會指向此額外參數。如果getopt()找不到符合的參數則會印出錯信息,並將全域變量optopt設爲“?”字符,如果不希望getopt()印出錯信息,則只要將全域變量opterr設爲0即可。
 
短參數的定義
       getopt()使用optstring所指的字串作爲短參數列表,象"1ac:d::"就是一個短參數列表。短參數的定義是一個'-'後面跟一個字母或數字,象-a, -b就是一個短參數。每個數字或字母定義一個參數。 
  其中短參數在getopt定義裏分爲三種:
  1. 不帶值的參數,它的定義即是參數本身。
  2. 必須帶值的參數,它的定義是在參數本身後面再加一個冒號。
  3. 可選值的參數,它的定義是在參數本身後面加兩個冒號 。
  在這裏拿上面的"1ac:d::"作爲樣例進行說明,其中的1,a就是不帶值的參數,c是必須帶值的參數,d是可選值的參數。
  在實際調用中,'-1 -a -c cvalue -d', '-1 -a -c cvalue -ddvalue', '-1a -ddvalue -c cvalue'都是合法的。這裏需要注意三點:
  1. 不帶值的參數可以連寫,象1和a是不帶值的參數,它們可以-1 -a分開寫,也可以-1a或-a1連寫。
  2. 參數不分先後順序,'-1a -c cvalue -ddvalue'和'-d -c cvalue -a1'的解析結果是一樣的。
  3. 要注意可選值的參數的值與參數之間不能有空格,必須寫成-ddvalue這樣的格式,如果寫成-d dvalue這樣的格式就會解析錯誤。

返回值
   getopt()每次調用會逐次返回命令行傳入的參數。
   當沒有參數的最後的一次調用時,getopt()將返回-1。
    當解析到一個不在optstring裏面的參數,或者一個必選值參數不帶值時,返回'?'。
   當optstring是以':'開頭時,缺值參數的情況下會返回':',而不是'?' 。
範例
#include <stdio.h>  
#include <unistd.h>  
 
int main(int argc, int *argv[])  
{  
        int ch;  
        opterr = 0;  
        while ((ch = getopt(argc,argv,"a:bcde"))!=-1)  
        {  
                switch(ch)  
                {  
                        case 'a':  
                                printf("option a:'%s'\n",optarg);  
                                break;  
                        case 'b':  
                                printf("option b :b\n");  
                                break;  
                        default:  
                                printf("other option :%c\n",ch);  
                }  
        }  
        printf("optopt +%c\n",optopt);  
}  
執行過程以及結果展示
$ ./getopt -a  
other option :?  
optopt +a  
$ ./getopt -b  
option b :b  
optopt +  
$ ./getopt -c  
other option :c  
optopt +  
$ ./getopt -d  
other option :d  
optopt +  
$ ./getopt -abcd  
option a:'bcd' 
optopt +  
$ ./getopt -bcd  
option b :b  
other option :c  
other option :d  
optopt +  
$ ./getopt -bcde  
option b :b  
other option :c  
other option :d  
other option :e  
optopt +  
$ ./getopt -bcdef  
option b :b  
other option :c  
other option :d  
other option :e  
other option :?  
optopt +f  


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