用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP