使用 getopt 访问命令行用户参数

Access to command line user arguments using getopt

我正在编写一个程序来处理来自用户的选项,并按照使用 getopt 编程的方式运行。我的问题是,如果用户输入无效选项,我该如何显示错误?另外,我想访问变量以便在错误消息中显示它。这是我的代码的快照:

#include <unistd.h>
#include <iostream>

int main(int argc, char **argv)
{
    enum {
        WHOLE, PREFIX, ANYWHERE, SUFFIX, EMBEDDED
    } mode;
    bool reverse_match = false;
    bool ignore_case = false;
    bool specify_length = false;

    int c;
    while ((c = getopt(argc, argv, "wpsavein:")) != -1) {
        switch (c) {
        case '?':
            std::cerr << "Unrecognised option " << std::endl;
            std::cerr << "Usage: match [-OPTION]... PATTERN [FILENAME]..." << std::endl;
            return 2;
            break;
        case 'w': // pattern matches whole word
            mode = WHOLE;
            break;
        case 'p': // pattern matches prefix
            mode = PREFIX;
            //cout << "test: " << optarg << endl;
            break;
        case 'a': // pattern matches anywhere
            mode = ANYWHERE;
            break;
        case 's': // pattern matches suffix
            mode = SUFFIX;
            break;
        case 'v': // reverse sense of match
            reverse_match = true;
            break;
        case 'e': // pattern matches anywhere
            mode = EMBEDDED;
            break;
        case 'i': // ignore case
            ignore_case = true;
            break;
        case 'n': // specifies length of match
            specify_length = true;
        }
    }
}

我使用 cerr 流来显示错误,但我希望它也包括用户输入。例如,如果用户输入 -t,错误将是:

Unrecognised option -t
Usage: match [-OPTION]... PATTERN [FILENAME]...

我得到的是:

invalid option -- 't'
Unrecognised option -t
Usage: match [-OPTION]... PATTERN [FILENAME]...

我相信 invalid option -- 't' 是默认值,但有什么方法可以修改或不包含它吗?并且还可以访问用户指定的选项?

getopt 手册片段:

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

您需要做的事情:

#include <unistd.h>
#include <iostream>

int main(int argc, char **argv) {
  opterr = 0;
  int c;
  while ((c = getopt(argc, argv, "wpsavein:")) != -1) {
    switch (c) {
      case '?':
        std::cerr << "Unrecognised option -" << static_cast<char>(optopt)
                  << std::endl;
        std::cerr << "Usage: match [-OPTION]... PATTERN [FILENAME]..."
                  << std::endl;
        return 2;
        break;
    }
  }
}