Subject: Re: Sample code in getopt(3)
To: Ben Harris <bjh21@netbsd.org>
From: Allen Briggs <briggs@wasabisystems.com>
List: tech-userlevel
Date: 06/24/2003 23:24:24
On Wed, Jun 25, 2003 at 12:49:01AM +0100, Ben Harris wrote:
> getopt(3) contains the following sample code for parsing -<number>
> options:
Well, there are two things I see. Andrew pointed out what the probable
intent is. First of all, note that this is listed in the "BUGS" section
of the man page... :-)
Minor nits:
'c' (or 'ch') should be declared.
'c' and 'ch': "pick one and stick with it"
The bug looks to be that the second branch of the 'if' should probably read
something like:
else {
length = atoi(argv[optind - 1] + 1);
optind++;
}
> Can anyone explain what the second branch of the "if" is for, and how to
> trigger it? For bonus points, explain how to add an extra option (say,
> "-a") in such a way that an argument of "-a0" doesn't cause a segfault
> there.
I suppose something like (untested):
char *p;
int ch;
int length, aflag;
length = 0; aflag = 0;
while ((ch = getopt(argc, argv, "0123456789")) != -1) {
switch (ch) {
case 'a':
aflag=1;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
p = argv[optind - 1];
if (p[0] == '-' && p[1] == ch && !p[2])
length = atoi(++p);
else {
length = atoi(argv[optind-1] + 1);
optind++;
}
break;
}
}
This has the nasty side-effect of '-a15' and '-15a' meaning different
things. Now how you fix this, I guess, depends on what semantics you're
looking for...
-allen
--
Allen Briggs briggs@wasabisystems.com
Wasabi Systems, Inc. http://www.wasabisystems.com/