c - 以非选项字符开头时 getopt_long() 失败

标签 c getopt-long

这是我的第一个使用 getopt_long() 的程序,所以如果这个问题很琐碎,请原谅我。

当传递给我的程序的第一个参数无效时,我遇到了问题

这是我的主要代码

int main(int argc, char * argv[])
{
  printf("----------------------------------------------\n\n");

  int fd[128];
  int fdCount=0;

  int c;
  int digit_optind =0;
  int verboseFlag=0;

  //to exit with this specific value collected from all functions
  int overallExitStatus=0;

  while(1)
    {

      int this_option_optind = optind ? optind : 1;
      int option_index =0;

      static struct option long_options[] = {

        {"rdonly",     optional_argument, 0,   'a'},
        {"wronly",     optional_argument, 0,   'b'},
        {"command",    optional_argument, 0,   'c'},
        {"verbose",    no_argument,       0,   'd'},
        {0,0,0,0}

      };
      c=getopt_long(argc,argv, "+", long_options, &option_index);

      if(c == -1)
        break;

      switch(c) {
      case 'a':
        rdonly(fd,&fdCount,verboseFlag,&optind,argc,argv);
        break;

      case 'b':
        wronly(fd,&fdCount,verboseFlag,&optind,argc,argv);
        break;

      case 'c':
        overallExitStatus +=command(fd,&optind,optarg,argc,argv,verboseFlag);
        break;

      case 'd':
        verboseFlag=1;
        break;

      case '?':
        break;

      default:
        printf("?? getopt returned character code 0%o ??\n", c);
      }
    }

   printf("Program is finished exiting with status %d\n",overallExitStatus);
  printf("----------------------------------------------\n\n");

  return overallExitStatus;
}

基本上,如果我按照以下方式启动我的程序

./myProgram a --rdonly file1.txt

程序不会解析任何参数,跳过开关并直接返回。

如果第一个参数以 - 或 -- 开头(即使它是一个错误的参数),程序将正确运行。

如何解决这个问题?

谢谢。

最佳答案

a 是一个有效的非选项(位置)参数,所以这就是 getopt_long 所假设的。

getopt_long 选项字符串中的 + 可防止选项参数重新排序,因此它不会向前查找 --rdonly 参数。即使您允许重新排序,a 也会被视为第一个位置参数。

关于c - 以非选项字符开头时 getopt_long() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824485/

相关文章:

perl - 强制使用标志 Getopt::Long

c - C getopt 和 getopt_long 是否仅适用于主要参数?

c - 通过套接字打包和发送二进制数据时出现问题 - 序列化

c - : do in a struct declaration after a member 是什么

c - USBHOSTHidKdb 固件代码中使用的函数 'number()' 的逻辑

perl - Perl 的 Getopt::Long 可以解析我没有提前定义的参数吗?

c - 使用 getopt 时出错

c++ - getopt_long 不打印错误消息

c - 如何从 ARM 汇编调用 C 函数?

C:解决在 HTTP 上下文中使用 select 时部分 header 的情况