2011年9月9日 星期五

c 分析命令列參數

標頭檔: unistd.h

原型:
int getopt(int argc, char * const argv[], const char *optstring);
說明:
用來分析命令列參數,引數argc和argv是由 main()傳遞的參數個數和內容。
參數 optstring 是有效選項(字母)。如 " a:bf"。代表要接受的option有 -a, -b, -f。
其中option a的後面是":"號,代表-a option後還有參數(例如-aext2)。
          getopt提供三個global variable :
          optarg: 像a:這樣的參數,getopt會將-a後面的字串放到optarg中。
          optopt: 有額外參數時,optopt 會儲存option,如果getopt()找不到符合的參數則會
                       列印錯誤,並將全域變數optopt設為'?'字元。
          opterr: 如果不希望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:cef"))!=-1)
  switch(ch)
 {
  case 'a':
     printf("choose a: %s\n",optarg);
     break;
  case 'c':
     printf("option c\n");
     break;
  case 'f':
    printf("option f\n");
    break;
  default:
    printf("other option: %c\n",ch);
    break;

 }
printf("optopt = %c\n",optopt);
}

結果:
[root@localhost shelltest]# ./test -acef   
choose a: cef
optopt = 
[root@localhost shelltest]# ./test -a   
other option: ?
optopt = a 
[root@localhost shelltest]# ./test -aaa
choose a: aa
optopt =
[root@localhost shelltest]# ./test -c
option c
optopt =
[root@localhost shelltest]# ./test -cc
option c
option c
optopt =
source code http://opencobol.add1tocobol.com/doxy/dc/d53/getopt_8c.html

沒有留言:

張貼留言