hel - 1 year ago 64
Linux Question

# How to judge the value of optind in getopt

I just want to test global variable optind and do the following test.How to judge the value of optind?

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
char optStr[] = "ab";
int c;

while ((c = getopt(argc, argv, optStr)) != -1) {
printf("optind: %d\n", optind);
switch (c) {
case 'a':
printf("-a\n");
break;
case 'b':
printf("-b\n");
break;
case '?':
printf("error\n");
break;
}
}

return 0;
}


./a.out -ab

optind: 1

-a

optind: 2

-b

next:

./a.out -a

optind: 2

-a

optind shows the index of next element to be processed in argv array.

So, when you do ./a.out -ab:

When a is evaluated, the next element to be processed in the argv is still 1, because b is not evaluated yet from argv[1].

When b is evaluated, the next element to be processed in the argv is 2, because argv[1] is completely processed.

When you do ./a.out -a:

When a is evaluated, the next element to evaluate is 2 because argv[1] is completely processed.

This is more clearly seen if you increase your options to say. optstr[] = "abcdef;". And call your program as ./a.out -abcdef. The optnid will be 2 only when the last option - i.e. f - is evaluated. Also, call ./a.out -a -b -c to see how optnid shows the next element to be processed in argv array.