I am working on a c project, which I am trying to write a program that allows users to use one of the command line options to invoke the program. For example
./program [-a or -b or -c] [-f filename] [-l length]
Which [-a or -b or -c]
is compulsory, and -f
and -l
is not.
My question is, how to return an error if users choose any two or more of the [-a or -b or -c]
at the same time?
This is allowed
./program -a -f -l
But not
./program -a -b -f -l
My thought is to use getopt()
to verify the options, but I am not sure how to do this.
Thank you for your time! Sorry if I ask something stupid.
CodePudding user response:
All getopt
does is make it easy to parse out command line options - it won't do any validation for you. You'll need to keep track of whether any of a
, b
, or c
have been set:
bool abcSet = false;
while( (c = getopt( argc, argv, "abcf:l:" )) != -1 )
{
switch( c )
{
case 'a':
if ( !abcSet )
{
// processing for a
abcSet = true;
}
else
// error, b or c already set
break;
case 'b':
// same as above
break;
case 'c':
// same as above
break;
...
}
You can play around with the sense of the test or how you want to keep track of which option is set, but you have to keep track of that information somehow.
CodePudding user response:
getopt
doesn't allow this degree of control.
There are two ways you can handle this:
- Anytime you read one of these options, check to see if one of the others was already read.
- After reading all options, check to see if more that one was given.