1

kindly help. I've gone all over online manuals... yet, no hint whats wrong.

The problem is that option_index does not get updated by getopt_long(), thus I'm unable to access proper struct members in form of long_options[option_index].name etc.

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

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

    int opt=0;
    int option_index=0;
    struct option long_options[]={
        {"first",   required_argument,  NULL,   'f'},
        {"second",  no_argument,        NULL,   's'},
        {"third",   required_argument,  NULL,   't'},
        {NULL,      0,                  NULL,   0}
    };

    while (1){
        option_index=0;
        opt=getopt_long (argc,argv, "f:st:", long_options, &option_index);
        if ( opt == -1 )
            break;

        printf("option %s", long_options[option_index].name);
        if (optarg)
            printf(" with arg %s", optarg);
        printf("\n");
    }

    return EXIT_SUCCESS;
}

Output :

# ~/workspace/Test/Debug/Test -f 1 -s -t third
option first with arg 1
option first
option first with arg third
  • Verified with debugger that option_index left unchanged during entire execution.

Thanks in advance, any idea / lead will be appreciated !

Vlad
  • 63
  • 1
  • 5
  • 1
    try `Test --first 1 --second --third third` – BLUEPIXY Aug 30 '14 at 22:30
  • That did the magic - thanks a lot, but now I'm confused - no way to get option_index when short option supplied ? * My program relies on checking if identified option expect optarg, I've counted on getting this from long_options[option_index].has_arg – Vlad Aug 30 '14 at 22:48
  • It is not used when you specify the short option. it can be tested in `if(long_options[option_index].flag == 0)` If the long option is used. – BLUEPIXY Aug 30 '14 at 22:50
  • If not much trouble : 1. Can you share link to source of this explanation (maybe I've missed something else ) 2. Any suggestion for work around in case short option supplied to know if corresponding long_option expects argument ? ( in my case I do not use flags, all zeroes ) Thank you. – Vlad Aug 30 '14 at 22:55
  • 1
    http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Options.html#Getopt-Long-Options – BLUEPIXY Aug 30 '14 at 23:13
  • Programmer knows a string of long option that corresponds to the short option. – BLUEPIXY Aug 30 '14 at 23:15
  • _in my case I do not use flags, all zeroes_ : It is a different story. – BLUEPIXY Aug 30 '14 at 23:17
  • @BLUEPIXY - Thanks for good will, effort and lead. I'll update here if will find any work around in described constrains. – Vlad Aug 30 '14 at 23:37

0 Answers0