C语言中的getopt()函数以解析命令行参数

getopt() function in C to parse command line arguments

getopt()是用于获取命令行选项的内置C函数之一。 该函数的语法如下:

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

操作字符串是字符列表。 它们每个代表一个字符选项。

此函数返回许多值。 这些如下所示-

  • 如果该选项采用一个值,则该值将由optarg指向。
  • 当没有更多选项继续时,它将返回-1
  • 返回"?" 为了表明这是一个无法识别的选项,它将其存储以供选择。
  • 有时某些选项需要一些值,如果该选项存在但这些值不存在,则它还将返回"?"。 我们可以使用':'作为optstring的第一个字符,因此在那个时候,它将返回':'而不是'?' 如果没有给出值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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
", option);
      break;
    case 'f': //here f is used for some file name
      printf("Given File: %s
", optarg);
      break;
    case ':':
      printf("option needs a value
");
      break;
    case '?': //used for some unknown options
      printf("unknown option: %c
", optopt);
      break;
   }
 }
 for(; optind < argc; optind++){ //when some extra arguments are passed
   printf("Given extra arguments: %s
", argv[optind]);
 }
}

输出量

1
2
3
4
5
Given Option: i
Given File: test_file.c
Given Option: l
Given Option: r
Given extra arguments: hello