0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that's a very clear explanation
How do you tell which of the options -a, -b or -c was set? I would probably use char abc_flag = 0; and then in each option handler, have code like if (abc_flag && abc_flag != c) err_error(”cannot use both option -%c and -%c\n”, abc_flag, c); abc_flag = c; break;. That records which flag was set as well as whether it was set. After the option parsing loop, check that abc_flag is set. This allows the user to repeat a flag. If that's not wanted, simplify the check (but maybe complicate the error reporting). Since the code is the same for all three options, you can combine them.
0

getopt doesn't allow this degree of control.

There are two ways you can handle this:

  1. Anytime you read one of these options, check to see if one of the others was already read.
  2. After reading all options, check to see if more that one was given.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.