Pergunta

So I have a pretty simple program but for some reason I can't get the options right.

  • If the -h option is present I just want to print the usage statement and exit.

  • If no options are present I want it to just run normally.

  • If any other options are present I want it to print the usage and EXIT_FAILURE

For some reason I just can't get these results. I know its a simple fix I just can't seem to find the answer.

Right now this is what I have.

int main(int argc, char* argv[]){
   int c;

   while(( c = getopt( argc, argv, "h")) != -1){
      switch( c ){
      case 'h':
         usage(); return EXIT_SUCCESS;

      case '*':
         usage(); return EXIT_FAILURE;

      default:
         break;
      }
   }
   mainProgram();
   return EXIT_SUCCESS;
}
Foi útil?

Solução

If you read the getopt(3) man page:

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

So, getopt() will return ? if someone passes in an unrecognized option. You're looking for *, which you will never receive. In C, * does not act as a wildcard so this does not mean "any character".

Using default here isn't the correct solution (although it will work), because this would also trigger on valid options for which you had not implemented a handler.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top