Parsing '?' in getopt

前端 未结 3 830
执念已碎
执念已碎 2021-01-17 05:48
void display(char * str){
   printf(\"%s: Missing file\\n\", str);
}

int main(int argc, char **argv)
{

    int longIndex, opt = 0;
    const char *optString = \"h?         


        
相关标签:
3条回答
  • 2021-01-17 06:02

    The question mark '?' is returned by getopt when it finds an argument that's not in the optstring or if it detects a missing option argument, so you shouldn't use '?' in optstring because it's sort of reserved for that, instead you should use the more conventional 'h' for help.

    See the man page

    Edit: This is an example:

    switch (opt) {
        case 'n':
            some_flag = 1;
            break;
        case 'h': /* help */
        default: /* '?' unknown opt or missing arg*/
            fprintf(stderr, "Usage: %s [-n nsecs] \n", argv[0]);
            exit(EXIT_FAILURE);
    }
    
    0 讨论(0)
  • 2021-01-17 06:08

    const char *optString = "h?";

    Above line replace with following line

    const char *optString = "h\?";

    this is the literal of question mark in C language

    0 讨论(0)
  • 2021-01-17 06:09

    If you include -? with --help on your help message, leave the question mark out of your call to getopt, leave it out of the case option, and make sure that --help is the first case option in your list, the question mark works as you'd want it to.

    0 讨论(0)
提交回复
热议问题