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是以':'開頭時,缺值引數的情況下會返回':',而不是'?' 。

範例 

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. int main(int argc, int *argv[])
  4. {
  5. int ch;
  6. opterr = 0;
  7. while ((ch = getopt(argc,argv,"a:bcde"))!=-1)
  8. {
  9. switch(ch)
  10. {
  11. case 'a':
  12. printf("option a:'%s'\n",optarg);
  13. break;
  14. case 'b':
  15. printf("option b :b\n");
  16. break;
  17. default:
  18. printf("other option :%c\n",ch);
  19. }
  20. }
  21. printf("optopt +%c\n",optopt);
  22. }

執行:

  1. $ ./getopt -a
  2. other option :?
  3. optopt +a
  4. $ ./getopt -b
  5. option b :b
  6. optopt +
  7. $ ./getopt -c
  8. other option :c
  9. optopt +
  10. $ ./getopt -d
  11. other option :d
  12. optopt +
  13. $ ./getopt -abcd
  14. option a:'bcd'
  15. optopt +
  16. $ ./getopt -bcd
  17. option b :b
  18. other option :c
  19. other option :d
  20. optopt +
  21. $ ./getopt -bcde
  22. option b :b
  23. other option :c
  24. other option :d
  25. other option :e
  26. optopt +
  27. $ ./getopt -bcdef
  28. option b :b
  29. other option :c
  30. other option :d
  31. other option :e
  32. other option :?
  33. optopt +f