c - getopt_long() fail when starting with non option character -


this first program uses getopt_long() please excuse me if questions trivial.

i having problem when first argument passed program invalid

here code main

int main(int argc, char * argv[]) {   printf("----------------------------------------------\n\n");    int fd[128];   int fdcount=0;    int c;   int digit_optind =0;   int verboseflag=0;    //to exit specific value collected functions   int overallexitstatus=0;    while(1)     {        int this_option_optind = optind ? optind : 1;       int option_index =0;        static struct option long_options[] = {          {"rdonly",     optional_argument, 0,   'a'},         {"wronly",     optional_argument, 0,   'b'},         {"command",    optional_argument, 0,   'c'},         {"verbose",    no_argument,       0,   'd'},         {0,0,0,0}        };       c=getopt_long(argc,argv, "+", long_options, &option_index);        if(c == -1)         break;        switch(c) {       case 'a':         rdonly(fd,&fdcount,verboseflag,&optind,argc,argv);         break;        case 'b':         wronly(fd,&fdcount,verboseflag,&optind,argc,argv);         break;        case 'c':         overallexitstatus +=command(fd,&optind,optarg,argc,argv,verboseflag);         break;        case 'd':         verboseflag=1;         break;        case '?':         break;        default:         printf("?? getopt returned character code 0%o ??\n", c);       }     }     printf("program finished exiting status %d\n",overallexitstatus);   printf("----------------------------------------------\n\n");    return overallexitstatus; } 

basically if start program in following way

./myprogram --rdonly file1.txt

the program not parse trough arguments, skips switch , goes straight return.

in case when first argument starts - or -- (even if wrong argument) program behaves correctly.

how can fix issue ?

thank you.

a valid non-option (positional) argument, that's getopt_long assumes is.

the + in getopt_long options string prevents reordering of option arguments, doesn't ahead --rdonly argument. if had allowed reordering, a treated first positional argument.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -