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