首页 > 解决方案 > 以任意顺序使用选项和参数解析命令行

问题描述

我很难考虑从命令行参数读取输入文件的方法,而参数可以以不同的方式排序。

例如:

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

但也可以订购命令行参数:

./a.out mazeData1.txt -d 

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

怎么能找到这样的输入文件?

标签: clinuxglibccommand-line-arguments

解决方案


这是 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;

}

推荐阅读