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

範例 

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

執行:

  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  

 

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