【问题标题】:two different command line argument in cc中的两个不同的命令行参数
【发布时间】:2015-01-06 07:00:47
【问题描述】:

我想解析两个不同的命令行参数:

文件 -f 某事 -o 某事

我在互联网上找到了一些代码并更改了它,但我无法解析它们。

int
main (int argc, char **argv)
{
  char *fvalue = NULL;
  char *ovalue = NULL;
  int index;
  int c;

  opterr = 0;
  while ((c = getopt (argc, argv, "fo:")) != -1)
    switch (c)
      {
      case 'f':
        fvalue = optarg;
        break;
      case 'o':
        ovalue = optarg;
        break;
      default:
        abort ();
      }
  printf ("fvalue = %s, ovalue = %s\n",
          fvalue, ovalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}

【问题讨论】:

  • 为什么不从 argv 访问参数? argv[2] 将持有 something1 和 argv[4] something2...
  • 我不知道该怎么做
  • argv 是一个字符串数组,其中包含您在命令行执行期间传递的所有参数(包括程序名称)。所以在你的情况下,当你运行“file -f something -o something”时,argv[0] 将是“file”,argv[1] 将是“-f”等等。如果你想打印它,你必须就像 printf("%s",argv[1]) 和 "-f" 会出现。希望我能帮上忙!
  • 非常感谢@TheDillo,我通过以下方式解决了这个问题,但我从你那里学到的东西真的很好

标签: c command-line-arguments


【解决方案1】:

你的optstring错了,一定是

while ((c = getopt (argc, argv, "f:o:")) != -1)

冒号表示该选项需要一个参数。

【讨论】:

    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2011-03-23
    • 2012-06-09
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多