我真的不明白如何使用 getopt_long 函数在 c 中正确处理命令行参数,我创建了这段代码:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main(int argc, char** argv) {
int next_option;
/* String of short options */
const char *short_options = "hl:k";
/* The array of long options */
const struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "launch", 1, NULL, 'l' },
{ "kill", 0, NULL, 'k' },
{ NULL, 0, NULL, 0 }
};
do {
next_option = getopt_long(argc, argv, short_options, long_options, NULL);
switch (next_option) {
case 'h':
/* User requested help */
fprintf(stdout, "HELP\n");
break;
case 'l':
fprintf(stdout, "launching\n");
fprintf(stdout, "Want to launch on port %s\n",\
optarg);
break;
case 'k':
fprintf(stdout, "KILLING\n");
break;
case '?':
/* The user specified an invalid option */
fprintf(stdout, "Requested arg does not exist!\n");
exit(EXIT_FAILURE);
case -1:
/* Done with options */
break;
default:
/* Unexpected things */
fprintf(stdout, "I can't handle this arg!\n");
exit(EXIT_FAILURE);
}
} while(next_option != -1);
return (EXIT_SUCCESS);
}
而且输出很奇怪,因为我们可以将垃圾数据作为命令行参数传递,而我的程序不检查此错误!我该如何解决。
执行示例:
$ ./command_line -h garbage
HELP
$ ./command_line --help garbage
HELP
$ ./command_line --launch 1200 garbage
launching
Want to launch on port 1200
$ ./command_line --lBADARG 1200
command_line: unrecognized option `--lBADARG'
Requested arg does not exist!
$ ./command_line -lBADARG 1200
launching
Want to launch on port BADARG
感谢您的帮助。
最佳答案
好的,发生的事情是这样的:
在这种情况下:
$ ./command_line --lBADARG 1200
command_line: unrecognized option `--lBADARG'
Requested arg does not exist!
通过给它 --lBADARG
你是在说寻找 LONG 参数 lBADARG
,但你没有。
在这种情况下:
$ ./command_line -lBADARG 1200
launching
Want to launch on port BADARG
您成功地告诉它使用带有参数的 -l
标志。它的行为符合预期,告诉您参数是 BADARG
。
如果你尝试
$ ./command_line -l 1200
或
$ ./command_line -l1200
或
$ ./command_line --launch 1200
那应该会如您所愿。而且,如果您想获取不是选项的参数,您会在完成 getopt 处理后 在 argv vector 中找到它们,因为 getopt_long 可以方便地置换argv vector 将非选项参数留在那里。
关于c - 我如何使用 getopt_long 处理 c 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8610693/