Search code examples
cgetopt

getopt_long setting optstring[0] to '+'


According to the man page for getopt and getopt_long, the GNU version reorders argv so that anything resembling a flag will be first, then it will return -1 when it reaches the first string that is not a flag. It also says that when optstring[0] is set to '+', it will not reorder the arguments. How do I set optstring[0] to '+'? I tried simply tossing in a optstring[0] = '+'; assignment statement, and I rightfully got that optstring is undeclared.


Solution

  • optstring is the third argument to getopt_long, declared as:

    int getopt_long(int argc, char * const argv[],
               const char *optstring,
               const struct option *longopts, int *longindex);
    

    Call the function with an optstring that begins with +:

    getopt_long(argc, argv, "+abc:d:f:", long_options, &option_index);