C 中的 getopt() 函数用于解析命令行参数
c++server side programmingprogramming
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 ':'在字符串的开头,以便编译器可以区分 '?' 和 ':' while((option = getopt(argc, argv, ":if:lrx")) != -1){ //从 getopt() 方法获取选项 switch(option){ //对于选项 i、r、l,打印这些是选项 case 'i': case 'l': case 'r': printf("Given Option: %c\n", option); break; case 'f': //此处 f 用于某些文件名 printf("Given File: %s\n", optarg); break; case ':': printf("option needs a value\n"); break; case '?': //用于某些未知选项 printf("unknown option: %c\n", optopt); break; } } for(; optind < argc; optind++){//当传递一些额外参数时 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