getopt 詳解 linux

 

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]就能得到下個字符串,通過判斷是否以 '-'開頭就可。下面是個測試程序
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
    int tmp = 4;
   
    while( (tmp = getopt(argc, argv, "abck")) != -1  )
    {
           
           printf("-%c/t", tmp);
           int opt = optind ;
           while( opt < argc )
           {
                  if ( argv[opt][0] != '-' )
                  {
                       printf("%s/t", argv[opt]);
                       opt ++;
                  }
                  else
                      break;
           }
           printf("/n");
    }
    getchar();
}
<script type="text/javascript"><!-- google_ad_client = "pub-6625678643128649"; google_alternate_color = "FFFFFF"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_type = "text_image"; google_ad_channel =""; //--></script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> <script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script> <script>window.google_render_ad();</script>

函數說明  getopt()用來分析命令行參數。參數argc和argv是由main()傳遞的參數個數和內容。參數optstring 則代表欲處理的選項字符串。此函數會返回在argv 中下一個的選項字母,此字母會對應參數optstring 中的字母。如果選項字符串裏的字母后接着冒號“:”,則表示還有相關的參數,全域變量optarg 即會指向此額外參數。如果getopt()找不到符合的參數則會印出錯信息,並將全域變量optopt設爲“?”字符,如果不希望getopt()印出錯 信息,則只要將全域變量opterr設爲0即可。

返回值  如果找到符合的參數則返回此參數字母,如果參數不包含在參數optstring 的選項字母則返回“?”字符,分析結束則返回-1。

範例  #include<stdio.h>
#include<unistd.h>
int main(int argc,char **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 –b
option b:b
$./getopt –c
other option:c
$./getopt –a
other option :?
$./getopt –a12345
option a:’12345’

getopt 函數

函數定義:
#include
int getopt(int argc, char * const argv[],
        const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;


#define _GNU_SOURCE
#include

int getopt_long(int argc, char * const argv[],
        const char *optstring,
        const struct option *longopts,
        int *longindex);

int getopt_long_only(int argc, char * const argv[],
        const char *optstring,
        const struct option *longopts,
        int *longindex);


getopt()函數是用來解析命令行參數的。這裏,主要解釋getopt_long()。

    getopt_long()的頭兩參數,argc和argv分別是傳遞給main()的參數的個數和參數數組(和main()的argc和argv是一個概念)。

    getopt_long()中,optstring是一個字符串,表示可以接受的參數。例如,"a:b:cd",表示可以接受的參數是a,b,c,d,其中,a和b參數後面

跟有更多的參數值。(例如:-a host --b name)

    getopt_long()中,參數longopts,其實是一個結構的實例:
struct option {
  const char *name;
   
//name表示的是長參數名
  int has_arg;
    //has_arg有3個值,no_argument(或者是0),表示該參數後面不跟參數值
    //   required_argument(或者是1),表示該參數後面一定要跟個參數值
    //   optional_argument(或者是2),表示該參數後面可以跟,也可以不跟參數值
  int *flag;
    //用來決定,getopt_long()的返回值到底是什麼。如果flag是null,則函數會返回與該項option匹配的val值
  int val;
    //和flag聯合決定返回值
}

給個例子:

struct option long_options[] = {
  {"a123",       required_argument,      0, 'a'},
  {"c123",       no_argument,            0, 'c'},
}

現在,如果命令行的參數是-a 123,那麼調用getopt_long()將返回字符'a',並且將字符串123由optarg返回(注意注意!字符串123由optarg帶

回!optarg不需要定義,在getopt.h中已經有定義)
那麼,如果命令行參數是-c,那麼調用getopt_long()將返回字符'c',而此時,optarg是null。

最後,當getopt_long()將命令行所有參數全部解析完成後,返回-1。

看來,我說的有點混亂,那麼,看個例子,我相信,代碼最能說明問題:

#include
#include
#include
#include

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

 struct option long_options[] = {
   {"a123",       required_argument,      0, 'a'},
   {"c123",       no_argument,            0, 'c'},
 }
 int opt;
 
 printf("starting... ");
 
 while((opt = getopt_long(argc, argv, "a:c", long_options, NULL)) != -1)
 {
  switch (opt)
  {
  case 'a':
    printf("It's a! ");
    printf("string of a:%s ",optarg);
  break;
    
  case 'c':
    printf("It's c! ");
  break;
    
  default:
    printf("You should look for help! ");
    exit(1);
  break;            
  }
 }
 printf("end... ");
 return 0;
}

編譯後,假設生成a.out,可以試驗一下。
./a.out -a hello -c
輸出:
starting...
It's a!
string of a:hello
It's c!
end...

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