【问题标题】:C forcing getopt to stop at first non argumentC强制getopt在第一个非参数处停止
【发布时间】:2014-11-23 13:45:02
【问题描述】:

我正在编写一个程序代理,它将标准输出等重定向到文件中,用法:proxy [-i infile] [-o outfile] [-e errfile] cmd [options]。

所以我想强制 getopt 在它到达 cmd 时停止,因为它不应该解析选项。

我阅读了有关环境变量 POSIXLY_CORRECT 的信息,但我想让它独立于它。

所以我的问题是如何做到这一点。

到目前为止我的部分代码

while ((opt = getopt (argc, argv, "i:o:e:")) != -1)
  switch (opt)
  {
    case 'i':
      i = 1;
      strcpy(input, optarg);
      break;
    case 'o':
      o = 1;
      strcpy(output, optarg);
      break;
    case 'e':
      e = 1;
      strcpy(error, optarg);
      break;
    default:
      fprintf(stderr, "usage: proxy [-i infile] [-o outfile] [-e errfile] <cmd> [options]\n");
      return -1;
  }

当给定 cmd 选项时,这将一直进入默认情况:(

【问题讨论】:

    标签: c getopt


    【解决方案1】:

    您被 GNU getopt 在进入前重新排序参数的可疑行为所困扰。如您所见,一种解决方案是在第一次调用getopt 之前设置环境变量POSIXLY_CORRECT。您还可以通过将+ 作为getopt 字符串的第一个字符传递来禁用此行为:

    opt = getopt(argc, argv, "+i:o:e:")
    

    【讨论】:

    • 很好,这个小“+”解决了我所有的问题 :) 非常感谢!
    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多