【问题标题】:Using getopt in C with non-option arguments在 C 中使用带有非选项参数的 getopt
【发布时间】:2021-06-24 10:37:27
【问题描述】:

我正在用 C 语言编写一个处理大量命令行参数的小程序,因此我决定使用 getopt 为我排序。

但是,我希望两个非选项参数(源文件和目标文件)是强制性的,因此在调用程序时必须将它们作为参数,即使没有标志或其他参数。

这是我必须处理带有标志的参数的简化版本:

while ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
    switch (c) {
        case 'i': {
            i = (int)atol(optarg);
        }
        case 'd': {
            d = (int)atol(optarg);
        }
        case 'b':
            buf = 1;
            break;
        case 't':
            time = 1;
            break;
        case 'w':
            w = (int)atol(optarg);
            break;
        case 'h':
            h = (int)atol(optarg);
            break;
        case 's':
            s = (int)atol(optarg);
            break;
        default:
            break;
    }
}

如何编辑它以便也处理非选项参数?

我还希望能够在选项之前 之后有非选项,那么如何处理呢?

【问题讨论】:

    标签: c arguments argv getopt getopt-long


    【解决方案1】:
    int main(int argc, char** argv) {
        
        
      char* inputfile;
      char* outputfile;
      char* output_file_type;
      char* color_red;
      char* color_blue;
      char* color_green;
      
      
      int opt;
      
      if (argv[optind] == NULL || argv[optind + 1] == NULL) {
      printf("Mandatory argument(s) missing\n");
      exit(1);
        }
     
      
      while((opt = getopt(argc, argv, ":i:o:r:g:b:t:")) != -1){
        switch(opt){
          case 'i':
            inputfile = optarg;
            printf("Input file : %s\n",inputfile);
            break;  
          case 'o':
            outputfile = optarg;
            printf("Output File: %s\n",outputfile);
            break;
          case 't':
            output_file_type = optarg;
            printf("Output File type: %s\n", output_file_type);
            break;
          case 'r':
            color_red = optarg;
            printf("Color Red: %s\n",color_red);
            break;
          case 'g':
            color_green = optarg;
            printf("Color Green: %s\n",color_green);
            break;
          case 'b':
            color_blue = optarg;
            printf("Color Blue: %s\n",color_blue);
            break;
          case ':':
            printf("option needs a value\n");
            break;
          case '?':
            printf("unknown option: %c\n", optopt);
            break;
        }
      
      }
      
      for (; optind < argc; optind++){
          
          
           printf("Given extra arguments: %s\n", argv[optind]);
         
       
      }  
    
    
        return (EXIT_SUCCESS);
    }
    

    运行命令:

    gcc main.c -o image
    ./image -i ./resource/input_file.bmp -o ./resource/output_file.bmp -t BPM -r 10 -g 24 -b 40
    

    输出:

    Input file : ./resource/input_file.bmp
    Output File: ./resource/output_file.bmp
    Output File type: BPM
    Color Red: 10
    Color Green: 24
    

    【讨论】:

      【解决方案2】:

      根据https://www.man7.org/linux/man-pages/man3/getopt.3.html

      默认情况下,getopt() 会在扫描时置换 argv 的内容, 所以最终所有的非选项都在最后。另外两个 还实现了扫描模式。如果第一个字符 optstring 为 '+' 或环境变量 POSIXLY_CORRECT 为 设置,则选项处理会在非选项参数出现时立即停止 遇到。如果 optstring 的第一个字符是 '-',那么 每个非选项 argv 元素都被当作参数处理 字符代码为 1 的选项。(这由程序使用 被写入期望选项和其他 argv 元素 任何顺序,并且关心两者的顺序。) 特殊参数“--”强制结束选项扫描 的扫描模式。

      【讨论】:

      • 虽然您的引文可能会告知手头的问题,但请。详细说明您对“如何编辑此问题以便也处理非选项参数?”问题的回答?
      【解决方案3】:

      非常好的例子可以在这里找到:GNU Libc 代码:

      #include <ctype.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <unistd.h>
      
      int
      main (int argc, char **argv)
      {
      int aflag = 0;
      int bflag = 0;
      char *cvalue = NULL;
      int index;
      int c;
      
      opterr = 0;
      
      while ((c = getopt (argc, argv, "abc:")) != -1)
      switch (c)
      {
      case 'a':
          aflag = 1;
          break;
      case 'b':
          bflag = 1;
          break;
      case 'c':
          cvalue = optarg;
          break;
      case '?':
          if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
          else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
          else
          fprintf (stderr,
              "Unknown option character `\\x%x'.\n",
              optopt);
          return 1;
      default:
          abort ();
      }
      
      printf ("aflag = %d, bflag = %d, cvalue = %s\n",
          aflag, bflag, cvalue);
      
      for (index = optind; index < argc; index++)
      printf ("Non-option argument %s\n", argv[index]);
      return 0;
      }
      

      它允许在参数之前和之后有选项。我确实编译并运行了测试示例:

      $ ./a.out aa ff bb -a -ctestparam hello
      aflag = 1, bflag = 0, cvalue = testparam
      Non-option argument aa
      Non-option argument ff
      Non-option argument bb
      Non-option argument hello
      

      【讨论】:

      • 这不适用于 Mac OSX 的 getopt 版本。
      • 在 linux glibc 中,optind 将指向强制参数,即使它们在 getopt() 之后位于选项后面
      【解决方案4】:

      getopt 设置optind 变量以指示下一个参数的位置。

      选项循环之后添加类似的代码:

      if (argv[optind] == NULL || argv[optind + 1] == NULL) {
        printf("Mandatory argument(s) missing\n");
        exit(1);
      }
      

      编辑:

      如果您想在常规参数之后允许选项,您可以执行类似的操作:

      while (optind < argc) {
        if ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
          // Option argument
          switch (c) {
              case 'i': {
                  i = (int)atol(optarg);
              }
              case 'd': {
                  d = (int)atol(optarg);
              }
              case 'b':
                  buf = 1;
                  break;
              case 't':
                  time = 1;
                  break;
              case 'w':
                  w = (int)atol(optarg);
                  break;
              case 'h':
                  h = (int)atol(optarg);
                  break;
              case 's':
                  s = (int)atol(optarg);
                  break;
              default:
                  break;
          }
          else {
              // Regular argument
              <code to handle the argument>
              optind++;  // Skip to the next argument
          }
      }
      

      【讨论】:

      • 好的,但是如果强制参数在可选参数之前,我的循环将退出,因此只会处理强制参数而不是可选参数。我该如何解决这个问题?
      • 通常要求选项位于参数之前。只需在man 页面中指定即可。
      • 是的,我知道,但是例如使用 ssh 命令,-p 标志可以出现在 强制 username@server 参数之后。我只是想知道怎么做
      • @gatopeich argv[argc] 由 C 标准保证为 NULL,所以我提供的代码应该可以正常工作。
      • 您在 EDIT 下提供的示例显然不起作用(至少在 Linux 上),我不敢相信自从首次发布以来没有人注意到这一点。
      猜你喜欢
      • 2014-03-22
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 2016-11-15
      • 2019-07-29
      相关资源
      最近更新 更多