Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 11 Sep 2006 11:57:14 -0700
From:      Chuck Swiger <cswiger@mac.com>
To:        Amarendra Godbole <amarendra.godbole@gmail.com>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Sequence of execution of getopt() and usage()...
Message-ID:  <7557EBA1-58B4-4EB9-B43E-6FE3416573F7@mac.com>
In-Reply-To: <294439d20609110527m2093cde8r4a93e391826f2b17@mail.gmail.com>
References:  <294439d20609110527m2093cde8r4a93e391826f2b17@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sep 11, 2006, at 5:27 AM, Amarendra Godbole wrote:
> This is a general FreeBSD source related question, and I am posting it
> here, as it did not fit in any other FreeBSD lists...

This list is a quite reasonable choice to ask such questions.  :-)

> While browsing through sources for different userland utilities (cat,
> chmod, and so on), I noticed that in main(), first getopt() is called
> in a while loop, and then the check for the number of arguments passed
> is done. Something like this (from chmod.c):
[ ... ]
> Can't we check for the number of arguments *before* calling getopt()?
[ ... ]
> I observe a similar pattern in other utilities too - which might mean
> that there was a sound reason as to why it was done this way. Can
> someone be kind enough to explain this? Thanks in advance!

Sure.  The issue is that utilities which require a certain number of  
arguments do not want to count the option flags being passed in, but  
argc's count includes these flags and any values being passed to  
flags which take a value (ie, getopt() options followed by a colon ":").

It's much easier to process the options and then do "argc -= optind",  
and then determine whether the remaining # of arguments left meet the  
criteria for the particular program.

-- 
-Chuck




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?7557EBA1-58B4-4EB9-B43E-6FE3416573F7>