用 C 中的 getopt() 函式解析命令列引數


getopt() 是用於接受命令列選項的內建 C 函式之一。此函式的語法如下 −

getopt(int argc, char *const argv[], const char *optstring)

opstring 是字元列表。其中每個字元表示單個字元選項。

此函式返回許多值。它們如下 −

  • 如果選項接受值,則該值將由 optarg 指向。
  • 如果沒有更多要處理的選項,則返回 -1
  • 返回“?”表示這是未識別的選項,它將其儲存在 optopt 中。
  • 有時某些選項需要一些值,如果選項存在但沒有值,則它也將返回“?”。我們可以使用“:”作為 optstring 的第一個字元,這樣,如果沒有給定值,它將返回“:”而不是“?”。

示例

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

main(int argc, char *argv[]) {
   int option;
   // put ':' at the starting of the string so compiler can distinguish between '?' and ':'
   while((option = getopt(argc, argv, ":if:lrx")) != -1){ //get option from the getopt() method
      switch(option){
         //For option i, r, l, print that these are options
         case 'i':
         case 'l':
         case 'r':
            printf("Given Option: %c\n", option);
            break;
         case 'f': //here f is used for some file name
            printf("Given File: %s\n", optarg);
            break;
         case ':':
            printf("option needs a value\n");
            break;
         case '?': //used for some unknown options
            printf("unknown option: %c\n", optopt);
            break;
      }
   }
   for(; optind < argc; optind++){ //when some extra arguments are passed
      printf("Given extra arguments: %s\n", argv[optind]);
   }
}

輸出

Given Option: i
Given File: test_file.c
Given Option: l
Given Option: r
Given extra arguments: hello

更新於: 30-Jul-2019

8K+ 瀏覽量

職業生涯從這裡啟程

完成課程即可獲得認證

開始
廣告
© . All rights reserved.