【问题标题】:How to make getopt_long() print nothing when there is error command-line arguments?当有错误的命令行参数时,如何使 getopt_long() 不打印任何内容?
【发布时间】:2017-06-08 12:16:28
【问题描述】:

我有一个程序使用getopt_get() 来解析命令行参数。 我的代码是这样的:

int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
}; 
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }   

当我将正确的命令行参数传递给程序时,它运行良好。 但是当错误的参数传递给程序时,它会打印出这样烦人的多余的词。

例如,我将错误的参数“q”传递给程序

$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t

当参数错误时,我只希望它运行我的函数help() 而不打印任何单词。

./program: invalid option -- 'q'

我怎样才能阻止getopt_long 打印这个烦人的单词而什么都不打印?

【问题讨论】:

    标签: c linux glibc getopt getopt-long


    【解决方案1】:

    阅读fine manual...

    如果getopt() 无法识别选项字符,则会打印错误 stderr 的消息,将字符存储在 optopt 中,并返回“?”。 调用程序可以通过将 opterr 设置为 0.

    所以,在致电getopt_long之前试试这个:

    opterr = 0;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2021-08-23
    相关资源
    最近更新 更多