linux系統呼叫getopt

uestczshen發表於2016-11-14

          函式說明 getopt()用來分析命令列引數。引數argc和argv分別代表引數個數和內容,跟main()函式的命令列引數是一樣的。

       引數 optstring為選項字串, 告知 getopt()可以處理哪個選項以及哪個選項需要引數,如果選項字串裡的字母后接著冒號“:”,則表示還有相關的引數,全域變數optarg 即會指向此額外引數。如果在處理期間遇到了不符合optstring指定的其他選項getopt()將顯示一個錯誤訊息,並將全域變數optarg設為“?”字元,如果不希望getopt()列印出錯資訊,則只要將全域變數opterr設為0即可。

       

getopt(分析命令列引數
相關函式
表標頭檔案 #include<unistd.h>
定義函式 int getopt(int argc,char * const argv[ ],const char * optstring);
extern char *optarg;
extern int optind, opterr, optopt;
getopt() 所設定的全域性變數包括:
optarg——指向當前選項引數(如果有)的指標。 optind——再次呼叫 getopt() 時的下一個 argv 指標的索引。 optopt——最後一個未知選項。
optstring中的指定的內容的意義(例如getopt(argc, argv, "ab:c:de::");)
1.單個字元,表示選項,(如上例中的abcde各為一個選項)
2.單個字元後接一個冒號:表示該選項後必須跟一個引數。引數緊跟在選項後或者以空格隔開。該引數的指標賦給optarg。(如上例中的b:c:)
3 單個字元後跟兩個冒號,表示該選項後可以跟一個引數,也可以不跟。如果跟一個引數,引數必須緊跟在選項後不能以空格隔開。該引數的指標賦給optarg。(如上例中的e::,如果沒有跟引數,則optarg = NULL)
示例:
#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 : printf("xxxtest");
  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);
  }
  return 0;
  }
執行 $./getopt –b
option b:b
執行 $./getopt –c
other option:c
執行 $./getopt –a
other option :?
執行 $./getopt –a12345
option a:’12345’
轉自getopt百度百科

相關文章