Can someone help me with the getopt function?
When I do the following in main:
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’m running this code on rhel3 which uses old libc version. I don’t know which one to be exact.
Now the problem is getopt doesn’t work the second time with argv2. But if I comment out the first getopt call with argv1 , it works.
Can someone tell me what am I doing wrong here?
argv1 and 2 must end in 0:
Edit: OK, I read the getopt man page and I found this:
So, making optind=1 between the two calls at getopt makes it work as expected.