【问题标题】:detecting no argument with getopt_long用 getopt_long 检测到没有参数
【发布时间】:2015-10-14 10:27:16
【问题描述】:

如何使用 getopt_long 检测用户未向程序传递参数?我可以通过检查 argc 检测到用户在没有参数的情况下调用程序,但是用户只用破折号调用我的程序呢?

$ my_prog -

我是否需要在我的 getopt 语句中包含此选项?

while(ca = getopt_long(argc, argv, "abc:D:",...)

函数会返回什么?

【问题讨论】:

  • 我猜 null 或 0。

标签: c command-line getopt getopt-long


【解决方案1】:

您可以使用optind 变量来确定此类参数:

变量 optind 是 argv[] 的下一个元素的索引 要处理的向量。它应由系统初始化为1, 并且 getopt() 将在它完成每个元素时更新它 argv[].

例如,

  for(int i = optind; i < argc; i++)
    printf("Unknown argument: %s\n", argv[i]);

您可以在处理参数后执行此操作,以确定是否有任何此类意外参数。

【讨论】:

    【解决方案2】:

    只需使用“-”字符开始您的 optstring。来自man getopt_long:

    如果 optstring 的第一个字符是 '-',那么每个非选项 argv 元素都被当作字符代码为 1 的选项的参数处理

    因此,如果您进入 while 循环,您可以假设使用 optstring "-abc:D:" 传递了一些参数。

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 1970-01-01
      • 2016-04-20
      • 2012-02-07
      • 2017-02-05
      • 2011-04-10
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多