linux中getopt的用法

linux中getopt的用法

getopt被用來解析命令行選項參數。就不用自己寫東東處理argv了。

#include <unistd.h>
       extern char *optarg;   //選項的參數指針
       extern int optind,    //下一次調用getopt的時,從optind存儲的位置處重新開始檢查選項。 
       extern int opterr,   //當opterr=0時,getopt不向stderr輸出錯誤信息。
       extern int optopt;   //當命令行選項字符不包括在optstring中或者選項缺少必要的參數時,該選項存儲在optopt中,getopt返回'?’、

       int getopt(int argc, char * const argv[], const char *optstring);
調用一次,返回一個選項。 在命令行選項參數再也檢查不到optstring中包含的選項時,返回-1,同時optind儲存第一個不包含選項的命令行參數。

首先說一下什麼是選項,什麼是參數。

字符串optstring可以下列元素,
1.單個字符,表示選項,
2.單個字符後接一個冒號:表示該選項後必須跟一個參數。參數緊跟在選項後或者以空格隔開。該參數的指針賦給optarg。
3 單個字符後跟兩個冒號,表示該選項後必須跟一個參數。參數必須緊跟在選項後不能以空格隔開。該參數的指針賦給optarg。(這個特性是GNU的擴張)。

getopt處理以'-’開頭的命令行參數,如optstring="ab:c::d::",命令行爲getopt.exe -a -b host -ckeke -d haha 
在這個命令行參數中,-a和-h就是選項元素,去掉'-',a,b,c就是選項。host是b的參數,keke是c的參數。但haha並不是d的參數,因爲它們中間有空格隔開。

還要注意的是默認情況下getopt會重新排列命令行參數的順序,所以到最後所有不包含選項的命令行參數都排到最後。
如getopt.exe -a ima -b host -ckeke -d haha, 都最後命令行參數的順序是: -a -b host -ckeke -d ima haha
如果optstring中的字符串以'+'加號開頭或者環境變量POSIXLY_CORRE被設置。那麼一遇到不包含選項的命令行參數,getopt就會停止,返回-1。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int result;

    opterr = 0; //使getopt不行stderr輸出錯誤信息

    while( (result = getopt(argc, argv, "ab:c::")) != -1 )
    {
           switch(result)
          {
              case 'a':
                  printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
                  break;
              case 'b':
                   printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'c':
                  printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
              case '?':
                    printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
            default:
                  printf("default, result=%c\n",result);
                  break;
          }
       printf("argv[%d]=%s\n", optind, argv[optind]);
    }
    printf("result=-1, optind=%d\n", optind);   //看看最後optind的位置

    for(result = optind; result < argc; result++)
         printf("-----argv[%d]=%s\n", result, argv[result]);

//看看最後的命令行參數,看順序是否改變了哈。
    for(result = 1; result < argc; result++)
         printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);
    return 0;
}

unistd裏有個 optind 變量,每次getopt後,這個索引指向argv裏當前分析的字符串的下一個索引,因此
argv[optind]就能得到下個字符串,通過判斷是否以 '-'開頭就可。


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