我真的不明白如何使用 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
谢谢你的帮助。