今天给大家提供一个用c实现的命令行解析程序,可以作为linux下的测试工具使用,这个实现相对来说还是比较广泛的,直接上代码:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main(int argc, char *argv[]) {
int opt;
int digit_optind = 0;
static struct option long_options[] = {
{"add", required_argument, NULL, 'a'},
{"append", no_argument, NULL, 'b'},
{"delete", required_argument, NULL, 'd'},
{"verbose", no_argument, NULL, 'v'},
{"create", required_argument, NULL, 'c'},
{"file", required_argument, NULL, 'f'},
{NULL, 0, NULL, 0}
};
int option_index = 0;
while ((opt = getopt_long(argc, argv, "a:bd:vc:f:", long_options, &option_index)) != -1) {
switch (opt) {
case 'a':
printf("Option --add with value `%s`\n", optarg);
break;
case 'b':
printf("Option --append\n");
break;
case 'd':
printf("Option --delete with value `%s`\n", optarg);
break;
case 'v':
printf("Option --verbose\n");
break;
case 'c':
printf("Option --create with value `%s`\n", optarg);
break;
case 'f':
printf("Option --file with value `%s`\n", optarg);
break;
default:
fprintf(stderr, "Usage: %s [-a add] [-b] [-d delete] [-v] [-c create] [-f file]\n", argv[0]);
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
printf("Non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}
这段代码主要利用了 getopt_long
函数来解析命令行参数。这个函数是 getopt
的扩展,支持长选项(例如 --help
)和短选项(例如 -h
)。下面是对代码中各个部分的详细解释:
引入头文件
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
这些头文件分别用于基本的输入输出、标准库函数和 getopt_long
函数的声明。
定义长选项
static struct option long_options[] = {
{"add", required_argument, NULL, 'a'},
{"append", no_argument, NULL, 'b'},
{"delete", required_argument, NULL, 'd'},
{"verbose", no_argument, NULL, 'v'},
{"create", required_argument, NULL, 'c'},
{"file", required_argument, NULL, 'f'},
{NULL, 0, NULL, 0}
};
这是一个结构体数组,每个结构体定义了一个长选项。这个结构体包括四个字段:
- name:选项的名称。
- has_arg:指定选项后是否需要跟参数。可以是
no_argument
(不跟参数)、required_argument
(必须跟参数)或optional_argument
(可选参数)。 - flag:如果不是 NULL,则是一个指针,指向一个变量,当选项被发现时,变量的值会设置为
val
。如果为 NULL,则直接将val
作为结果返回。 - val:是一个字符,通常与对应的短选项相同。
解析选项
int option_index = 0;
while ((opt = getopt_long(argc, argv, "a:bd:vc:f:", long_options, &option_index)) != -1) {
switch (opt) {
// 根据不同的选项做出反应
}
}
这里用 getopt_long
函数循环处理所有的命令行输入。getopt_long
的参数包括命令行参数的数量和数组、一个包含短选项定义的字符串以及长选项数组。每次循环,它会返回下一个选项字符,当所有选项都被处理后返回 -1。
处理各个选项
switch (opt) {
case 'a':
printf("Option --add with value `%s`\n", optarg);
break;
case 'b':
printf("Option --append\n");
break;
// 更多选项的处理...
}
在 switch
语句中,根据返回的 opt
字符执行相应的操作。如果选项需要参数(如 -a
),getopt_long
会在全局变量 optarg
中设置这个参数。
处理额外的非选项参数
if (optind < argc) {
printf("Non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
optind
是 getopt
函数用来存储下一个要处理的参数的索引。如果 optind
小于 argc
,表示还有非选项参数未处理。这部分代码打印所有未被选项处理的命令行参数。