Tuesday, August 7, 2007

getopt Keeps Internal State

Here's the solution to a problem that's been bothering me at work for two days now:

If you want to use getopt more than once within a program, across different inputs, you'll need to reset its internal state counters before each use:

printf("%d %d %d\n",optind,opterr,optopt);
... do getopt stuff ...
printf("%d %d %d\n",optind,opterr,optopt);

This outputs the following:

1 1 63
3 1 63

the '3' in my case is because I only had one option + parameter (+ program name == 3).

So, if you reset optind, opterr and optopt to 1, 1 and 63, before each new use of getopt, you should be fine.

-- Courtesy of DanielLawson and the Waikato Linux Users Group

No comments: