【问题标题】:Parsing command line with options and parameters in any order以任意顺序使用选项和参数解析命令行
【发布时间】:2021-01-27 10:14:46
【问题描述】:

我在考虑从命令行参数读取输入文件的方法时遇到了麻烦,而参数可以以不同的方式排序。

例如:

./a.out -d mazeData1.txt   would read the input file from argv[2] 

但命令行参数也可以排序:

./a.out mazeData1.txt -d 

^ 现在输入文件在 argv[1] 中

如何找到这样的输入文件?

【问题讨论】:

  • 您需要使用getopt()来管理选项(即以“-”开头的参数),然后您才能获取最后一个非选项参数。
  • 您可能会更新您的标题以匹配您的实际问题。读取文件与您的问题无关。这都是关于解析命令行参数的。

标签: c linux glibc command-line-arguments


【解决方案1】:

这是 getopt() 的第一种简单方法。请参阅手册 (man 3 getopt) 了解更多信息:

#include <unistd.h>
#include <stdio.h>

int main(int ac, char *av[])
{
  int opt;
  extern int optind;

  while ((opt = getopt(ac, av, "d")) != -1) {

    switch(opt) {

      case 'd': {

        printf("-%c option\n", opt);   

      }
      break;

      default: {

        printf("Unknown option\n");
        return 1;
      }

    }

  }

  if (av[optind]) {
    printf("First non option parameter: %s\n", av[optind]);
  }

  return 0;

}

【讨论】:

  • POSIX 符合 getopt() 在第一个非选项参数处停止,因此它不会在 OP 的第二个示例中看到 -d。 (另一方面,除非设置了 POSIXLY_CORRECT 环境变量,否则 GNU 版本会看到它)。
猜你喜欢
  • 2016-02-06
  • 1970-01-01
  • 2014-12-04
  • 2014-12-22
  • 2014-09-18
  • 2013-03-06
  • 2011-10-29
  • 2017-08-31
  • 1970-01-01
相关资源
最近更新 更多