Let's say I made a C program that is called like this:
./something -d dopt filename
So -d
is a command, dopt
is an optional argument to -d
and filename
is an argument to ./something
, because I can also call ./something filename
.
What is the getopt
form to represent get the filename?
Use optstring "d:"
Capture -d dopt
with optarg
in the usual way. Then look at optind
(compare it with argc
), which tells you whether there are any non-option arguments left. If so, your filename is the first of these.
getopt
doesn't specifically tell you what the non-option arguments are or check the number. It just tells you where they start (having first moved them to the end of the argument array, if you're in GNU's non-strict-POSIX mode)
Check-out how grep does it. At the end of main()
you'll find:
if (optind < argc)
{
do
{
char *file = argv[optind];
// do something with file
}
while ( ++optind < argc);
}
The optind
is the number of command-line options found by getopt. So this conditional/loop construct can handle all of the files listed by the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With