linux getopt_long用法
时间: 2023-06-24 13:05:14 浏览: 59
`getopt_long` 是一个 C 语言的函数,用于解析命令行参数。与传统的 `getopt` 函数不同,`getopt_long` 支持长选项(如 --help)和短选项(如 -h)。
下面是 `getopt_long` 的基本用法:
```c
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main(int argc, char *argv[]) {
int c;
int digit_optind = 0;
while (1) {
int option_index = 0;
static struct option long_options[] = {
{"add", required_argument, 0, 0 },
{"append", no_argument, 0, 0 },
{"delete", required_argument, 0, 0 },
{"verbose", no_argument, 0, 0 },
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 0 },
{0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "abc:d:012",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b\n");
break;
case 'c':
printf("option c with value '%s'\n", optarg);
break;
case 'd':
printf("option d with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc) {
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}
```
上面的代码演示了 `getopt_long` 的基本用法。其中 `long_options` 数组定义了长选项的名称、参数类型以及对应的短选项(如果有的话)。在调用 `getopt_long` 函数时,第三个参数为短选项字符串,其中冒号表示该选项需要参数。
函数返回值为下一个选项的字符编码,或者 -1 表示已经解析完所有选项。如果选项需要参数,则该参数存储在全局变量 `optarg` 中。
更多关于 `getopt_long` 的用法,可以参考其官方文档:http://man7.org/linux/man-pages/man3/getopt_long.3.html