Thread: getopt and multiple options

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    1

    getopt and multiple options

    I'm having a problem with getopt where it won't accept multiple options.

    Let's say I have this:

    ./program -a <optarg> -b <optarg>

    getopt only seems to recognize and return the first switch (-a) and totally ignores the second (-b).

    Perhaps I'm overlooking something?

    Edit: Nevermind! The counter in my loop was set wrongly.
    Last edited by bej; 11-11-2005 at 04:57 PM.

  2. #2
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246
    you call getopt in a loop and it returns the next arg or if there aren't any then -1 is returned.
    :wq

  3. #3
    Just kidding.... fnoyan's Avatar
    Join Date
    Jun 2003
    Location
    Still in the egg
    Posts
    275
    Hi

    are you looking for something like this ?

    Code:
            const char *s_option="hi:n:p:v";
            const struct option l_option[]={
                     { "help",      0, NULL, 'h'},
                     { "ip",        1, NULL, 'i'},
                     { "nm",        1, NULL, 'n'},
                     { "port",      1, NULL, 'p'},
                     { "version",   0, NULL, 'v'},
            };
    
    // Now, looking for the supplied arguments and options
            do {
                    n_opt=getopt_long(argc,argv,s_option,l_option,NULL);
                    switch(n_opt){
                            case 'h':
                            case '?':
                                    usage(argv[0],0);
                                    break;
                            case 'i':
                                    printf("i\n%s\n",optarg);
                                    break;
                            case 'n':
                                    printf("n\n%s\n",optarg);
                                    break;
                            case 'p':
                                    printf("p\n%s\n",optarg);
                                    break;
                           case 'v':
                                    printf(" %s version %s\n",argv[0],VERSION_INFO);                                                     exit(0);
                            case -1:
                                    break;
                            default:
                                    abort();
                    } /* switch */
            } while (n_opt!=-1);
    a small modified part from one of my codes...

Popular pages Recent additions subscribe to a feed