繁体   English   中英

使用getopt_long处理用户错误

[英]Handling user error with getopt_long

我如何处理用户仅在长参数版本之前输入一个破折号的情况?

例如,使用-copy运行我的程序

$ my_program -copy
Copy
Open
my_program: invalid option -- p
Unknown

执行了o选项是一个问题。 我的目的是显示一个错误报告,这种思维定式是“您在一个破折号后键入了多个字符”。

编码

#include <getopt.h>
#include <stdio.h>

int main( int argc, char *argv[] )
{
  struct option options[] =
  {
    {"open",  no_argument, 0, 'o'},
    {"copy", no_argument, 0, 'c'},
    {0, 0, 0, 0}
  };

  int c;
  int option_index = 0;
  while ( ( c = getopt_long( argc, argv, "oc", options, &option_index ) ) != -1 )
  {
    switch (c)
    {
    case 'o':
      printf( "Open\n" );
      break;
    case 'c':
      printf( "Copy\n" );
      break;
    default:
      printf( "Unknown\n" );
      return 0;
    }
  }

  return 0;
}

除了手动解析命令行外,没有其他方法可以执行此操作。 getopt_long()假设长选项以--开头,并且如果您不希望-- ,则无需输入长选项。 无论如何,关于用户是否确实忘记了- ,或者用户是否真的认为存在py短选项,充其量是模棱两可的,程序无法区分这两种情况。

但是,如果需要,您可以做的是将getopt_long()替换为getopt_long_only() ,该方法允许使用单个-来指定长选项。 在您的特定情况下, -copy将被替换为--copy ,因此您无需报告错误。 显然,这种方式增加了歧义匹配的可能性。

修改后的代码:

#include <getopt.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    struct option options[] = {
        {"open", no_argument, 0, 'o'},
        {"copy", no_argument, 0, 'c'},
        {0, 0, 0, 0}
    };

    int c;
    int option_index = 0;
    while ((c = getopt_long_only(argc, argv, "oc",
                                 options, &option_index)) != -1) {
        switch (c) {
        case 'o':
            printf("Open\n");
            break;
        case 'c':
            printf("Copy\n");
            break;
        default:
            printf("Unknown\n");
            return 0;
        }
    }

    return 0;
}

并输出:

paul@local:~/src/sandbox$ ./go -copy
Copy
paul@local:~/src/sandbox$ 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM