为什么 C getopt_long_only() 不为未知选项设置 optopt?

Why does C getopt_long_only() not set optopt for unknown option?

我正在尝试将 getopt_long_only() 用于自定义错误消息。代码如下所示。我尝试设置 opterr=0 并在 optstring 的开头使用冒号来禁用内置错误消息。我添加了一个由布尔值 optoptWorks = true 控制的代码块来尝试自定义错误消息,例如在使用 -z 这样的错误选项时打印一条消息。但是 optopt 始终设置为 0,我使用的 ? 错误消息没有意义。 ':'(冒号大小写)错误(缺少参数,例如 -d)对于自定义消息确实有效。关闭内置错误消息并在 ? 中处理似乎会导致 optopt 始终设置为 0,因此我无法打印有问题的选项 (-z is not recognized)。我在 Debian Linux gcc 4.9.4 和 Cygwin gcc 7.3.0 上编译,结果相同。 getopt_long_only() 似乎没有正确设置 optopt 还是我遗漏了什么?网络上的许多示例通过使用内置错误消息或仅打印用法而不告诉用户哪个选项无法识别来解决这个问题。

这是 optoptWorks=false 的输出:

$ ./testoptget -z
testoptget: unknown option -- z

-d #            Set the debug level.
-h, --help      Print program usage.
-q              Run in quiet mode (log messages to syslog but not console).
-v, --version   Print program version.

$ ./testoptget -d
testoptget: option requires an argument -- d

-d #            Set the debug level.
-h, --help      Print program usage.
-q              Run in quiet mode (log messages to syslog but not console).
-v, --version   Print program version.

这里是 optoptWorks=true:

的输出
$ ./testoptget -z
[ERROR] Unknown option character '\x0'.

-d #            Set the debug level.
-h, --help      Print program usage.
-q              Run in quiet mode (log messages to syslog but not console).
-v, --version   Print program version.

$ ./testoptget -d
[ERROR] Option '-d' is missing argument.

-d #            Set the debug level.
-h, --help      Print program usage.
-q              Run in quiet mode (log messages to syslog but not console).
-v, --version   Print program version.

代码如下:

/*
Test program for getopt_long_only
*/

#include <ctype.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int debug = 0; /* Default to not debugging */

/**
Print the program usage.
*/
void usage(void)
{
    /* Print the program name and version */
    printf("\n");
    printf("-d #            Set the debug level.\n");
    printf("-h, --help      Print program usage.\n");
    printf("-q              Run in quiet mode (log messages to syslog but not console).\n");
    printf("-v, --version   Print program version.\n\n");
    exit(0);
}

/**
Parse command line parameters and set data for program.
@param argc number of command line parameters
@param argv list of command line parameters
*/
void parseargs(int argc,char **argv)
{   /*
    See:  https://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt
    See:  http://man7.org/linux/man-pages/man3/getopt.3.html

    Because legacy -version and --version need to be supported, use getopts_long_only.
    */

    /*
    The meaning of the following is:
    name - the name of the long option
    has_arg - whether the option has an argument like --arg param or --arg=param
    flag - the numeric value to return (set to "opt" below), if NULL or zero, return "val"
    val - the value to return (set to "opt" below) if "flag" not set, use the one-character equivalent
    */
    static struct option long_options[] = {
        { "help",    no_argument, 0, 'h' }, /* returns as if -v, index not needed */
        { "version", no_argument, 0, 'v' }, /* returns as if -h, index not needed */
        { 0,         0,           0, 0 }    /* last element of array must be zeros */
    };
    int long_index = 0;
    int opt;
    int errorCount = 0;
    /* In <unistd.h>:  external int optind, opterr, optopt */
    bool optoptWorks = false;  /* Apparently optopt gets set to 0 for unknown argument so let the getopt_long_only print the error */
    char optstring[32] = "d:hqv";
    if ( optoptWorks ) {
        /*
        If getopt_long_only works as it is supposed to...
        Set opterr to zero so getopt calls won't print an error - check for errors in '?' return value
        Also use : as first character of optstring to cause : to be used for error handling
        */
        opterr = 0;
        /* Do the following because strcat is not safe on overlapping strings */
        char optstring2[32];
        strcpy(optstring2,optstring);
        strcpy(optstring,":");
        strcat(optstring,optstring2);
    }
    while((opt = getopt_long_only(argc, argv, optstring, long_options, &long_index)) != -1) {
        switch (opt) { /* Will match single character option or long_options val or flag */
            case 'd':
                /* -d #, Set the debug level to the argument value */
                debug = atoi(optarg);
                break;
            case 'h':
                /*
                -h, print the usage and exit
                -help
                --help
                */
                usage();
                exit(0);
                break;
            case 'q':
                /* -q, indicate that messages should not be printed to stdout */
                break;
            case 'v':
                /*
                -v, print the version via standard function,
                -version
                --version
                */
                break;
            case ':':
                /*
                This is an error indicator indicated by : at the start of get_opt_long 3rd argument.
                Handle missing argument, such as -d but no argument.
                */
                fprintf(stderr, "[ERROR] Option '-%c' is missing argument.\n", optopt);
                ++errorCount;
                break;
            case '?':
                /*
                Handle unknown parameters as per getopt man page example.
                "optopt" should contain the offending argument, but perhaps matches last long argument (zero record).
                Note that legacy ? command line parameter is no longer supported.
                */
                if (isprint(optopt)) {
                    /* Printable character so print it in the warning. */
                    if ( optoptWorks ) {
                        fprintf(stderr, "[ERROR] Unknown option '-%c'.\n", optopt);
                    }
                    ++errorCount;
                }
                else {
                    /* Nonprintable character so show escape sequence. */
                    if ( optoptWorks ) {
                        fprintf(stderr, "[ERROR] Unknown option character '\x%x'.\n", optopt);
                    }
                    ++errorCount;
                }
                break;
        } /* end switch */
    } /* end while */
    if ( errorCount > 0 ) {
        usage();
        exit(1);
    }
}

/**
Main program.
@param argc number of command line parameters
@param argv list of command line parameters
@param arge list of environment variables
*/
int main(int argc,char **argv,char **arge)
{
    /* Parse command arguments */
    parseargs(argc,argv);

    /* Normal program termination */
    return(0);
}

optopt 确实在发现未知的长选项时设置为零,请参阅 getopt returns '?'.[=36= 之前的 here. However seems to me you can use optind - 1 as the index in argv to print the offending option, as optind is incremented here ]

据我了解,您的目标只是指定自定义错误消息。

也来自男人 getopt_long:

If the first character (following any optional '+' or '-' described above) of optstring is a colon (':'), then getopt() likewise does not print an error message. In addition, it returns ':' instead of '?' to indicate a missing option argument. This allows the caller to distinguish the two different types of errors.

您引用的文档是关于 getopt 的,而不是关于 getopt_long_only 的。 man getopt_long_only 确实表示 getopt_long() function works like getopt()optopt 设置为 "option character"。在长选项的情况下,没有 "option character",而是 "option string"(我会这样称呼它)- 在我看来,将 optopt 设置为零是合乎逻辑的。

因此,根据 optstring 中的初始字符,返回 :?,如实施的那样 here and here and here

以下程序是您的程序,删除了注释,缩短了使用功能,用 exit 替换了 return 并添加了仅 printf("%s", argv[opting - 1]);:

的打印违规选项
#include <ctype.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int debug = 0;

void usage(void) { printf("-- insert usage here --\n"); }

void parseargs(int argc,char **argv)
{
    static struct option long_options[] = {
        { "help",    no_argument, 0, 'h' },
        { "version", no_argument, 0, 'v' },
        { 0,         0,           0, 0 }
    };
    int long_index = 0;
    int opt;
    int errorCount = 0;

    optind = 1;

    while((opt = getopt_long_only(argc, argv, ":d:hqv", long_options, &long_index)) != -1) {
        switch (opt) {
            case 'd':
                debug = atoi(optarg);
                break;
            case 'h':
                usage();
                return;
                break;
            case 'q':
                break;
            case 'v':
                break;
            case ':':
                fprintf(stderr, "[ERROR] Option '-%c' is missing argument.\n", optopt);
                ++errorCount;
                break;
            case '?':
                if (optopt == 0) {
                    fprintf(stderr, "[ERROR] Unknown option '%s'.\n", argv[optind - 1]);
                } else {
                    fprintf(stderr, "[ERROR] Error parsing option '-%c'\n", optopt);
                }
                ++errorCount;
                break;
        }
    }
    if ( errorCount > 0 ) {
        usage();
        return;
    }
}

int main(int argc, char **argv)
{

#define SIZE(x) (sizeof(x)/sizeof(*x))
    struct {
        int argc;
        char **argv;
    } tests[] = {
        { 2, (char*[]){ argv[0], (char[]){"-z"}, NULL, } },
        { 2, (char*[]){ argv[0], (char[]){"-d"},  NULL, } },
    };

    for (int i = 0; i < SIZE(tests); ++i) {
        printf("\n## test tests[i].argv[1] = %s\n", tests[i].argv[1]);
        parseargs(tests[i].argc, tests[i].argv);
    }

    return 0;
}

输出:

## test tests[i].argv[1] = -z
[ERROR] Unknown option '-z'.
-- insert usage here --

## test tests[i].argv[1] = -d
[ERROR] Option '-d' is missing argument.
-- insert usage here --

如果 optstring 设置为 "d:hqv" 而没有前导 :,则它属于 ? 的情况,即。然后程序 returns:

## test tests[i].argv[1] = -z
./a.out: unrecognized option '-z'
[ERROR] Unknown option '-z'.
-- insert usage here --

## test tests[i].argv[1] = -d
./a.out: option requires an argument -- 'd'
[ERROR] Error parsing option '-d'
-- insert usage here --