Parsing '?' in getopt

前端 未结 3 860
执念已碎
执念已碎 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);
    }
    

提交回复
热议问题