【问题标题】:Why is libargtable behaving strangely with optional arguemnts?为什么 libargtable 与可选的争论行为奇怪?
【发布时间】:2012-08-31 15:35:50
【问题描述】:

如果有人使用 argtable 作为 C 代码的 命令行参数解析器,这是我的问题:

我的意图

我正在使用最新版本的 argtable2 库在 Linux 平台上使用 C 语言进行编程。

我想要归档的是有一个接受多个输入文件和一个可选选项的程序(我们称之为-o)。如果-o 未提供作为 shell 调用中的选项,则程序不会写入任何输出。如果-o由它自己提供,程序的输出将写入一个名为“output.txt”的默认文件。如果选项与文件名一起提供,例如-o other.txt输出应写入给定的文件名 - 在本例中为“other.txt”。

问题

在我所有的尝试中 argtable 行为不端。它解释与-o 一起给出的可选值作为输入文件。所以./program -o other.txt inputfile1.dat inputfile2.dat inputfile3.dat 会被解释为有四个输入文件——三个“inputfile*.dat”和应该是输出文件的“other.txt”。

重现问题

这是一个shell会话来说明,我的意思。它使用产生问题的minimal example。我不确定是我做错了什么还是libargtable2 中的错误:

confus@confusion:~$ gcc -o argbug argbug.c -largtable2
confus@confusion:~$ ./argbug
Error: missing option INPUT-FILES

Usage:
./argbug [-o [<file>]] INPUT-FILES
-o [<file>]               File to write output to. Default is 'output.txt'.
                         Omit whole option to discard all output
INPUT-FILES               Input files
confus@confusion:~$ ./argbug inputfile1.dat inputfile2.dat inputfile3.dat -o other.txt
inputfile[0] = inputfile1.dat              # this is okay output
inputfile[1] = inputfile2.dat              # as is this line
inputfile[2] = inputfile3.dat              # also okay output
inputfile[3] = other.txt                   # "other.txt" is falsely recognized as an input file
outputfile = output.txt                    # should be "other.txt" instead of the default "output.txt"

无论是我还是 Steward,argtable 的作者似乎都没有时间真正研究我的问题。有什么想法吗?

【问题讨论】:

  • 看起来你的要求是模棱两可的:图书馆如何决定你是指-o之后的文件名是输入还是输出? -o input.txt 看起来和 -o output.txt 完全一样

标签: c shared-libraries command-line-arguments


【解决方案1】:

我运行了您的测试并发现了同样的问题。查看源代码,似乎 libargtable 正在正确处理它,但归结为 getopt 行为。

如果您从 getopt.c 中的第 647 行开始查看,您会看到 getopt 首先检查是否有附加参数选项和参数之间没有任何空格(例如 -oother.文本)。如果是这种情况,它会处理它。这是它会注意到可选参数的唯一情况。

要对此进行测试,请尝试

void *argtable[] = { argOutput, end };

在你的测试用例中,然后

./argbug -o other.txt

你会看到它给出了一个错误。

但是,它还有一段额外的代码,用于检查是否有必需的选项。如果是这样,即使标志和参数之间有空格,is 也会执行额外的搜索来满足这一点。

查看代码的提示:has_arg 是一个枚举,其中 0=无参数 1=必需的参数 2=可选参数

简答

如果标志和参数之间有空格,libargtable 将不会处理可选参数。删除空间,它应该可以工作。

我可能认为这是一个错误,但也许有些人喜欢这种行为。

【讨论】:

  • 谢谢,我注意到 ./argbug -oother.txt 可以工作,并认为这是底层 getopt 中的错误。我向 Steward 报告了这件事,但我们都在攻读博士学位,没有时间做任何事情。
  • 我猜 getopt 作者会认为它是一个特性,而不是一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
相关资源
最近更新 更多