Command line processing library - getopt

Can someone help me with getopt function?

When I do the following basically:

char *argv1[] = {"testexec","-?"};
char *argv2[] = {"testexec","-m","arg1"};
int  cOption;
/* test for -? */

setvbuf(stdout,(char*)NULL,_IONBF,0);
printf("\n argv1 ");
while (( cOption = getopt (2, argv1, "m:t:n:fs?")) != -1) {
    switch(cOption){
        case 'm':
            printf("\n -m Arg : %s \n",optarg);
            break;
        case '?':
            printf("\n -? Arg ");
            break;
        case 'n':
            printf("\n -n Arg : %s \n",optarg);
            break;
    }
}

printf("\n argv2 ");

while (( cOption = getopt (3, argv2, "m:t:n:fs?")) != -1) {
    switch(cOption){
        case 'm':
            printf("\n -m Arg : %s \n",optarg);
            break;
        case '?':
            printf("\n -? Arg : %s \n",optarg);
            break;
        case 'n':
            printf("\n -n Arg : %s \n",optarg);
            break;
    }
}

I am running this code on rhel3, which uses the old version of libc. I do not know which one was accurate.

Now the getopt problem does not work a second time with argv2. But if I comment on the first getopt call with argv1, it works.

Can someone tell me what I'm doing wrong here?

+5
source share
4 answers

argv1 and 2 should end with 0:

char* argv1[] = {"par1", "par2", 0};

Edit: Ok, I read the getopt man page and I found this:

optind - , argv.         1. reset 1, argv .

, optind = 1 getopt, , .

+12

getopt() , optind optarg, . , , , . reset getopt , , , , , , , ; , ( , getopt() , ). . . getopt() , .

, reset getopt (, , , )... , - , , : -/

+4

:

", GNU, '+' '-' optstring, POSIXLY_CORRECT , getopt(), optind 0, 1. ( 0 , POSIXLY_CORRECT GNU optstring.)"

+2

, getopt_long()? getopt() _getopt_long() . , ( ), Linux, BSD , HelenOS, , , getopt libc:)

, , , , .

getopt_long() ( ) , "" , , (, ), , .

This makes it easy to compare the number of arguments with the number of options actually passed in both calls, with many other benefits. Please do not use an outdated interface.

Look at getopt.h, you will see what I mean.

+1
source

All Articles