把第一个操作数在getopt的() [英] Put operands first in getopt()

查看:138
本文介绍了把第一个操作数在getopt的()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 getopt的()函数C,就可以做到这一点:

Using the getopt() function in C, it is possible to do that:

program -a arg_for_a -b arg_for_b -c operand1 operand2

和它没有问题的工作原理。

and it works with no problem.

但是,如何让它以这种方式工作:

But, how to make it work this way?:

program operand1 operand2 -a arg_for_a -b arg_for_b -c

在这种情况下,每一个参数,包括 -a -b 等,都被认为是操作数

In this case, every argument, including the -a, -b etc. are considered to be operands.

我想对刚才喜欢就好 GCC SSH 所做的:

I'm trying to make just like like gcc or ssh does:

gcc code.c -o executable
ssh user@host -i file.pem

也就是说,无论在什么位置的选项和操作数来,他们被正确识别。

That is, no matter in what position the options and the operands come, they are recognized properly.

如何让无论他们选择正确识别上,凡不按选项字识别操作数?

How to make options be recognized properly wherever they are, and every word that do not follow an option be recognized an operand?

推荐答案

如果您使用GNU C库的实现getopt的,那么它会像所有的GNU工具做的,因为几乎所有的人都使用它。特别是,(从男子3 getopt的报价

If you use the GNU C library's implementation of getopt, then it will work like all GNU utilities do, because almost all of them use it. In particular, (quoting from man 3 getopt):

默认getopt的()permutes的argv的内容作为它扫描,以便最终所有nonoptions是在端

By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end.

这是不太一样的 GCC GCC 关心的可选的位置参数的相对顺序。 (例如,它有差别,其中 -l <​​/ code>进入命令行)。为了做到这一点,你必须告诉GNU getopt的来的的置换参数。然后,每次 getopt的的报告,它的完成, OPTIND 将下一个位置参数的索引(如果有的话) 。然后,您可以用这样的说法,增量 OPTIND ,并继续使用 getopt的,这将继续下一个参数。

That's not quite the same as gcc. gcc cares about the relative order of optional and positional arguments. (For example, it makes a difference where -l goes in the command line.) To do that, you'll have to tell GNU getopt to not permute the arguments. Then, every time getopt reports that it's done, optind will have the index of the next positional argument (if any). You can then use that argument, increment optind, and continue using getopt, which will continue at the next argument.

这篇关于把第一个操作数在getopt的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆