是否可以通过 getopt_long 参数列表向后移动?
我想根据特定参数是否存在来委托给几个可能的参数列表之一,大致如下:
./test --do-thing-1 --option-A=7 --common-option --option-B=2 # options C and D not valid
./test --do-thing-2 --option-C=9 --common-option --option-D=1 # options A and B not valid
我能想到的巧妙地做到这一点的最佳方法是使用 main() 处理所有常见选项,并决定调用几个函数中的哪一个来处理剩余部分。
请注意,我不想限制顺序,以便常见选项只能首先出现。
我的问题是,如果我在第二次解析参数之前将 optind
重置为 1,则 getopt_long
会通过将无效字符串传递给 strncmp
来出现段错误 -所以我想我不应该搞乱 optind 。
我谷歌了一下,找不到任何关于是否可以跳过 getopt_long 参数列表的参考(我知道 getopt 是可能的),如果是,我该怎么做?
我不想使用任何非标准库。 (语言是纯c,请不要使用c++)
I would like to delegate to one of several possible lists of arguments based on whether particular arguments are present, along the lines of:
./test --do-thing-1 --option-A=7 --common-option --option-B=2 # options C and D not valid
./test --do-thing-2 --option-C=9 --common-option --option-D=1 # options A and B not valid
And the best way I can think of to do this neatly is to have main()
process all the common options, and decide which of several functions to call to process the remainder.
Note that I don't want to restrict the order so that common options can only occur first.
My problem is that if I reset optind
to 1 before parsing the arguments for a second time, getopt_long
segfaults by passing an invalid string to strncmp
- so I guess I shouldn't be messing with optind.
I've had a google, and can't find any reference on whether it is possible to jump around the getopt_long
argument list (I know it is possible for getopt
), if it is, how do I do it?
I would prefer not to use any non-standard libraries. (Language is plain c, no c++ please)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的问题是我没有将静态结构选项 long_options[] 数组的最后一行设置为零,正确设置可以修复错误。
GNU getopt 还要求将 optind 重置为 0 而不是 1,以便正确重置其内部状态。
My problem was that I hadn't set the last row of my
static struct option long_options[]
array to zeros, setting this correctly fixes the error.GNU getopt also requires
optind
to be reset to 0 not 1 in order to correctly reset its internal state.