Manuel Manuel - 2 months ago 20
C Question

Getopt - with a required entry

I got to do a program that would be called :

>./program [-p] [-h] [-n <number>] <file>

I got my getopt working but I need to get the file somehow, I tried with
but the
can be given before any of the flags.
Possible calls are:

>./program bomber.txt
>./program bomber.txt -n 2 -p
>./program -h bomber.txt -n 4
>./program -p -n 3 bomber.txt


You can find the documentation for getopt at

The actual answer to your question is in the following paragraph

By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end. Two other modes are also implemented. If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered. If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.) The special argument "--" forces an end of option-scanning regardless of the scanning mode.

The key point is that getopt permutes the command line. When you have finished parsing al the options, argv[optind] will reference the mandatory filename.

If the filename is not present in the command line, optind will be equal to argc.