getopt和getopt_long的使用
都是Linux下用来解析命令行参数的函数, 前者只能解析短选项, 后者可以处理短选项和长选项
短选项指的是: -t这种, 长选项指的是: --time这种
getopt
1 函数原型
int getopt(int argc, char * const argv[], const char *optstring);
argc和argv就是main函数传入的参数
opstring表示短选项字符串-
2 opstring例子
"a:b::cd"
- a:表示支持-a后带参数
- b::表示支持-b可带可不带
- c表示支持选项-c
3 返回值
If an option was successfully found, then getopt() returns the option character. If all command-line options have been parsed, then getopt() returns -1. If getopt() encounters an option character that was not in optstring, then '?' is returned. If getopt() encounters an option with a missing argument, then the return value depends on the first character in optstring: if it is ':', then ':' is returned; otherwise '?' is returned.
(man手册说明)
* 匹配成功, 返回选项字符, 比如-a返回a(循环调用,多次返回)
* 如果到了末尾, 返回-1
* 如果缺少参数, 决定于opstring第一个字符串(如果时:返回:,否则返回?)
* 如果解析到一个不是opstring中的字符串返回-1
4 全局变量optind
表示的是下一个将被处理到的参数在argv中的下标值, 初始为1
如果最后发现, optind5 示例
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
exit(EXIT_SUCCESS);
}
getopt_long
- 1 函数原型
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
longopts表示长选项结构体
struct option
{
const char *name;
int has_arg;
int *flag;
int val;
};
* name 表示名称
* hash_arg表示是否带参数:no_argument(0,不带参数), required_argument(1, --time 1/--time=1), optional_argument(3,--time=1)
* flag 如果为NULL, 当选中某个长选项时,将返回val值(第四个)
* 如果不是NULL,将返回0,将flag指向val
2 全局变量
optarg: 当前选项对应的参数值
optind: 下一个将被处理的arg的index值
opteer: 如果为0,不会输出错误信息到标准输出
optopt: 表示没有被未标识的选项3 示例可以自行翻阅man手册
4 getopt_long会修改argv的顺序, 不是-选项的参数会被移动到最后, 在解析完毕后, 可以通过argc和optind获取单独的参数值!