[轉] 關於C語言中getopt()函數的使用方法

在Linux中,用命令行執行可執行文件時可能會涉及到給其加入不同的參數的問題,例如:
./a.out -a1234 -b432 -c -d

程序會根據讀取的參數執行相應的操作,在C語言中,這個功能一般是靠getopt()這個函數,結合switch語句來完成的,首先來看下面的代碼:
#include <stdio.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
  int ch;
  opterr=0;
  
  while((ch=getopt(argc,argv,"a:b::cde"))!=-1)
  {
    printf("optind:%d/n",optind);
    printf("optarg:%s/n",optarg);
    printf("ch:%c/n",ch);
    switch(ch)
    {
      case 'a':
        printf("option a:'%s'/n",optarg);
        break;
      case 'b':
        printf("option b:'%s'/n",optarg);
        break;
      case 'c':
        printf("option c/n");
        break;
      case 'd':
        printf("option d/n");
        break;
      case 'e':
        printf("option e/n");
        break;
      default:
        printf("other option:%c/n",ch);
    }
    printf("optopt+%c/n",optopt);
  }

}    

用gcc編譯後,在終端行執行以上的命令:
./a.out -a1234 -b432 -c -d

則會有如下的輸出:
optind:2
optarg:1234
ch:a
option a:'1234'
optopt+
optind:3
optarg:432
ch:b
option b:'432'
optopt+
optind:4
optarg:(null)
ch:c
option c
optopt+
optind:5
optarg:(null)
ch:d
option d
optopt+

要理解getopt()函數的作用,首先要清楚帶參數的main()函數的使用:
main(int argc,char *argv[])中的argc是一個整型,argv是一個指針數組,argc記錄argv的大小。上面的例子中。
argc=5;
argv[0]=./a.out
argv[1]=-a1234
argv[2]=-b432
argv[3]=-c
argv[4]=-d
getopt()函數的原型爲getopt(int argc,char *const argv[],const char *optstring)。
其中argc和argv一般就將main函數的那兩個參數原樣傳入。
optstring是一段自己規定的選項串,例如本例中的"a:b::cde",表示可以有,-a,-b,-c,-d,-e這幾個參數。
“:”表示必須該選項帶有額外的參數,全域變量optarg會指向此額外參數,“::”標識該額外的參數可選(有些Uinx可能不支持“::”)。
全域變量optind指示下一個要讀取的參數在argv中的位置。
如果getopt()找不到符合的參數則會印出錯信息,並將全域變量optopt設爲“?”字符。
如果不希望getopt()印出錯信息,則只要將全域變量opterr設爲0即可。
發佈了23 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章