【问题标题】:How to use no_argument in getopt_long in?如何在getopt_long中使用no_argument?
【发布时间】:2014-03-02 13:35:38
【问题描述】:

我正在尝试将 getopt_long 用于我的代码。 optional_argument 和 required_argument 选项可以正常工作,但 no_Argument 选项不能正常工作。这就是我的编码方式。

struct option long_option[] = 
{
  {"auto",required_argument,0,'a'},
  {"help",no_argument,0,'h'},
  {"list",no_argument,0,'l'},
  {0,0,0,0}
};

现在,如果我编译并尝试:

./a.out --help 

--> 显示所有帮助内容

./a.out --help 1234 

--> 仍然显示所有帮助内容。应该提示不需要参数的错误??

【问题讨论】:

    标签: c getopt-long


    【解决方案1】:

    不,这不被视为错误。 getopt_long1234 解释为程序参数。

    在这个例子中更清楚:

    rm -r -f dir1/ dir2/
    

    这里-r-f 是选项,dir1/dir2/ 都是程序参数。 注意,如果你执行rm file1.txt -f,它会尝试删除一个名为“-f”的文件。

    【讨论】:

    • "...它将尝试删除一个名为 -f." 的文件。这实际上取决于rm 的实现。事实上,它在最近的 Linux 上没有。
    • 好的,我明白了,但是结构中的 no_argument 选项有什么用?为了使这件事起作用,我是否必须在 switch 循环内的“case 'h'”中使用 if/else 循环来检查 --help/--list 之后是否有任何程序参数?
    猜你喜欢
    • 1970-01-01
    • 2012-01-26
    • 2012-02-07
    • 1970-01-01
    • 2017-02-19
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多