Search code examples
cgetopt

how to limit the using of command line options in c using getopt()?


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.


Solution

  • 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.