【问题标题】:getopt_long() fail when starting with non option charactergetopt_long() 以非选项字符开头时失败
【发布时间】:2016-01-16 07:08:24
【问题描述】:

这是我第一个使用 getopt_long() 的程序,所以如果这个问题是微不足道的,请原谅我。

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

这是我的 main 代码

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

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

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

我该如何解决这个问题?

谢谢。

【问题讨论】:

    标签: c getopt-long


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多