Getopt - 需要输入

Getopt - with a required entry

我必须编写一个名为 :

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

我的 getopt 可以正常工作,但我需要以某种方式获取文件,我尝试使用 optind<file> 可以在任何标志之前给出。 可能的调用是:

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

您可以在 https://linux.die.net/man/3/getopt

找到 getopt 的文档

您问题的实际答案在以下段落中

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.

重点是getopt置换了命令行。解析完所有选项后,argv[optind] 将引用强制文件名。

如果命令行中没有文件名,optind 将等于 argc