Subject: Re: Sample code in getopt(3)
To: der Mouse <mouse@Rodents.Montreal.QC.CA>
From: Andrew Brown <atatat@atatdot.net>
List: tech-userlevel
Date: 06/24/2003 22:21:30
>> while ((c = getopt(argc, argv, "0123456789")) != -1) {
>> switch (c) {
>> 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);
>> break;
>> }
>> }
>
>> Can anyone explain what the second branch of the "if" is for, and how
>> to trigger it?
>
>It makes no sense to me. My first reaction is that it's intended to
>handle multi-digit arguments (which won't trip the first case because
>of the !p[2] test), but in that case it needs to be [optind-1], and as
>you point out gets confused when a digit option is merged in the same
>argument as a non-digit option.
it's supposed to differentiate between -3 and -37 as options. -3 will
match the former case (and optind will have been incremented). -37
will match the latter case (since option flag eating will not be done
yet).
>Part of the problem is that using getopt like this is ambiguous. Is
>"foo -56" supposed to be equivalent to "foo -5 -6"? getopt simply is
>not suitable for cases like this where options can sometimes be
>multiple characters long (as opposed to options with arguments, which
>is another schizoid area of getopt); trying to shoehorn it into a fit
>is going to be uncomfortable at best, and I'm not surprised it breaks
>something.
-56 won't be equivalent to -5 -6. the former case will set length to
56, whereas the latter will set it to 6 (-6 overrides -5 since it
comes later).
--
|-----< "CODE WARRIOR" >-----|
codewarrior@daemon.org * "ah! i see you have the internet
twofsonet@graffiti.com (Andrew Brown) that goes *ping*!"
werdna@squooshy.com * "information is power -- share the wealth."