Can I use getopt to process options in a certain o

2020-03-31 06:27发布

I'm implementing a command line tool, and I need to be able to handle a bunch of options. Some of the options must terminate the program after they're done. For example I have options a, b and c. If a and b terminate after their done, and I give the command

./myprogram -bca [file] 

Is there a way to give "a" precedence in a situation like this using getopt()?

EDIT:

I solved this by running a switch on the options and set a flag if an option was selected. Then sent all the flags to a function that looks at the flags in order.

标签: c getopt
2条回答
够拽才男人
2楼-- · 2020-03-31 07:16

There are two main ways to process the options read by getopt(). One is to do the action associated with an option as getopt() identifies it before reading the rest of the options; the other is to read all the options before doing any processing. (Programs not infrequently implement hybrid solutions; some options are acted on while parsing the arguments but others are simply noted and the actions taken after the arguments are processed.)

In your situation, it seems likely that you need to parse all the options before doing any processing. If both -a and -b terminate the program after doing the action, then they're mutually exclusive options and you should probably diagnose that as an erroneous invocation of your program. You will need to decide whether it is OK to allow -c as well as either -a or -b.

Quite often, you will have pairs of options that are required to work together, or you need to know whether one, the other, or both have been specified before deciding what to do. Another issue to consider is what it means if an option is repeated on the command line.

查看更多
3楼-- · 2020-03-31 07:19

There is no way to make getopt itself handle this. The easiest way would be to create a flags bitmap, as @tfahl suggested.

查看更多
登录 后发表回答