I'm writing a simple code making use of *argv[]
parameter. I'd like to know whether I can use getopt()
function for the following intent.
./myprogram -a PATH
./myprogram PATH
The program can either take merely PATH
(e.g. /usr/tmp
) or take -a
option in addition to PATH
. Can getopt()
be used for this state? If can, how?
Certainly. I'm not sure where you even see a potential issue, unless its that you don't appreciate POSIX's and
getopt()
's distinction between options and arguments. They are related, but not at all the same thing.getopt()
is fine with the case that no options are in fact specified, and it gives you access to the non-option arguments, such asPATH
appears to be for you, regardless of how many options are specified. The usual usage model is to callgetopt()
in a loop until it returns-1
to indicate that no more options are available from the command line. At each step, the global variableoptind
variable provides the index of the nextargv
element to process, and aftergetopt()
(first) returns -1,optind
provides the index of the first non-option argument. In your case, that would be where you expect to findPATH
.Using an optstring of
"a"
allows an argument of-a
to act as a flag.optind
helps detect that only one additional argument is present.The program can be executed as
./program -a path
or./program path