简体   繁体   中英

C - getopt incorrectly interprets next option as argument for previous option

I'm using getopt the following way:

     while ((c = getopt(argc, argv, ":a:b")) != -1) {
        switch (c) {
        case 'a':
          printf("option: a argument: %s\n", optarg);
          break; 
        case 'b':
          printf("option: b\n");
          break;
        case ':':
          if(optopt == 'a') {
            printf("option: a argument: default\n");
          else {
            fprintf(stderr, "argument required!\n");
          }
    }

The idea is to have option a take an optional argument, and use a default if none is provided.

However, if I run my program like this: ./main -a -b , what ends up getting printed is:

option a: argument -b

What I want is:

option: a argument: default
option: b

How can I get getopt to realize what's following -a is in fact another option and not its argument?

getopt incorrectly interprets next option as argument for previous option

No, getopt correctly interprets the next argument as an argument, as it should.

How can I get getopt to realize what's following -a is in fact another option and not its argument?

You cannot - getopt does not support optional arguments. You may: accept the limitations, roll your own option parsing method or use a different utility for option parsing.

from the MAN page:

optstring is a string containing the legitimate option characters.   If
   such  a  character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text  in  the  same
   argv-element,  or  the  text  of the following argv-element, in optarg.
   Two colons mean an option takes an optional arg;

therefore, this: ":a:b" would be better written as: `"a::b" which allows '-a' to have an optional argument and 'b' to have no argument.

read the details for getopt and how to use getopt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM