Put the operands first in getopt ()

Using the getopt() function in C, you can do this:

 program -a arg_for_a -b arg_for_b -c operand1 operand2 

and it works without problems.

But how to make it work this way ?:

 program operand1 operand2 -a arg_for_a -b arg_for_b -c 

In this case, each argument, including -a , -b , etc., is considered an operand.

I am trying to make it like gcc or ssh does:

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

That is, regardless of the position in which the options and operands are, they are recognized properly.

How to correctly determine the parameters, wherever they are, and each word that does not follow the option must be recognized by the operand?

+2
source share
1 answer

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

By default, getopt () rearranges the contents of argv when it is viewed, so that ultimately all non-opposition ends.

This is not exactly the same as gcc . gcc takes care of the relative order of optional and positional arguments. (For example, it matters where -l goes on the command line.) To do this, you will need to tell GNU getopt not to rearrange the arguments. Then, each time getopt reports what it has done, optind will have the index of the next positional argument (if any). Then you can use this argument, increment optind and continue using getopt , which will continue with the next argument.

+3
source

Source: https://habr.com/ru/post/982676/


All Articles