【问题标题】:getopt compatibility across platformsgetopt 跨平台兼容性
【发布时间】:2011-07-28 09:21:01
【问题描述】:

我目前正在用 C 语言编写一个简单的程序,它可以接受数字命令行参数。但我也希望它有命令行选项。如果其中一个数字参数为负数,我注意到不同操作系统之间的不一致(即 getopt 有时会/有时不会混淆 -ve 作为参数)。例如:

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

int main(int argc, char* argv[])
{
  char ch;

  while ((ch = getopt(argc, argv, "d")) != -1) {
    switch (ch) {
    case 'd':
      /* Dummy option */
      break;
    default:
      printf("Unknown option: %c\n", ch);
      return 1;
    }
  }
  argc -= optind;
  argv += optind - 1;

  if (argc < 2) {
    fprintf(stderr, "Not enough arguments\n");
    return 1;
  }

  float f = atof(argv[1]);
  printf("f is %f\n", f);
  float g = atof(argv[2]);
  printf("g is %f\n", g);
  return 0;
}

如果我在 Mac 和 Cygwin 下编译并运行这个程序,我会得到以下行为:

$ ./getopttest -d 1 -1
f is 1.000000
g is -1.000000

但如果我在 Windows 上的 Ubuntu 和 MingW 上尝试相同的操作,我会得到:

$ ./getopttest -d 1 -1
./getopttest: invalid option -- '1'
Unknown option: ?

显然,将数字参数和选项放在一起有点错误 - 但是有没有办法让 getopt 以一致的方式运行?

【问题讨论】:

    标签: c gcc getopt


    【解决方案1】:

    使用-- 将选项与非选项分开。

    $ ./getopttest -d -- 1 -1
    

    永远不会尝试读取-1 作为选项。

    【讨论】:

    • 已更正 - 是的。这样可行。我需要使用“./getopttest -d -- 1 -1”。谢谢:-)
    • 实际上,问题是我没有给予足够的关注。让我更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多