getopt多字符例子
时间: 2023-09-12 09:13:20 浏览: 55
我可以为您提供一个getopt多字符的例子,您可以参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
int main(int argc, char **argv) {
int c;
int option_index = 0;
static struct option long_options[] = {
{"mode", required_argument, 0, 'm'},
{"name", required_argument, 0, 'n'},
{"file", required_argument, 0, 'f'},
{0, 0, 0, 0}
};
char *mode_arg = NULL;
char *name_arg = NULL;
char *file_arg = NULL;
while ((c = getopt_long(argc, argv, "m:n:f:", long_options, &option_index)) != -1) {
switch (c) {
case 'm':
mode_arg = optarg;
break;
case 'n':
name_arg = optarg;
break;
case 'f':
file_arg = optarg;
break;
default:
printf("Usage: %s -m [mode] -n [name] -f [file]\n", argv[0]);
exit(EXIT_FAILURE);
}
}
printf("Mode: %s\n", mode_arg ? mode_arg : "not specified");
printf("Name: %s\n", name_arg ? name_arg : "not specified");
printf("File: %s\n", file_arg ? file_arg : "not specified");
return 0;
}
```
在这个例子中,我们使用了多个getopt_long的选项,并通过长选项(`--mode`, `--name`, 和 `--file`)来指定一些参数值。您可以在运行时使用`-m`, `-n` 和 `-f` 简短的选项来代替长选项。
注意,如果您希望在没有指定选项时使用默认值,则需要在循环内检查相应的变量是否为NULL,并输出"not specified"的提示信息。