c - 我如何使用 getopt_long 处理 c 中的参数

标签 c command-line-arguments getopt-long

我真的不明白如何使用 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/

相关文章:

C 结构体声明

java - 如何检查是否给出了命令行参数?

c - 带有重复和可选参数的 getopt

c++ - getopt 参数取决于另一个

c++ - 连接命令行参数的最佳方法

c - getopt_long : only modify flag if user supplied command-line option

python - 从 api 模拟多行 shell 行为

C:下标值既不是数组也不是指针

c++ - 什么时候需要显式指针类型转换?

assembly - MIPS:从命令行参数读取字符串