int getopt( int argc, char *const argv[], const char *optstring );
给定了命令参数的数量 (argc
)、指向这些参数的数组 (argv
) 和选项字符串 (optstring
) 后,getopt()
将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有识别到的选项,将返回 -1
,此任务就完成了。
getopt()
所设置的全局变量包括:
optarg
——指向当前选项参数(如果有)的指针。optind
——再次调用getopt()
时的下一个 argv 指针的索引。optopt
——最后一个已知选项。
对于每个选项,选项字符串 (optstring
) 中都包含一个对应的字符。具有参数的选项(如示例中的 -l
和 -o
选项)后面跟有一个 :
字符。示例所使用的 optstring
为 Il:o:vh?
(前面提到,还要支持最后两个用于打印程序的使用方法消息的选项)。
可以重复调用 getopt()
,直到其返回 -1
为止;任何剩下的命令行参数通常视为文件名或程序相应的其他内容。
/* doc2html supports the following command-line arguments:
*
* -I - don't produce a keyword index
* -l lang - produce output in the specified language, lang
* -o outfile - write output to outfile instead of stdout
* -v - be verbose; more -v means more diagnostics
* additional file names are used as input files
*
* The optString global tells getopt() which options we
* support, and which options have arguments.
*/
struct globalArgs_t {
int noIndex; /* -I option */
char *langCode; /* -l option */
const char *outFileName; /* -o option */
FILE *outFile;
int verbosity; /* -v option */
char **inputFiles; /* input files */
int numInputFiles; /* # of input files */
} globalArgs;
static const char *optString = "Il:o:vh?";
opt = getopt( argc, argv, optString ); while( opt != -1 ) { switch( opt ) { case 'I': globalArgs.noIndex = 1; /* true */ break; case 'l': globalArgs.langCode = optarg; break; case 'o': globalArgs.outFileName = optarg; break; case 'v': globalArgs.verbosity++; break; case 'h': /* fall-through is intentional */ case '?': display_usage(); break; default: /* You won't actually get here. */ break; } opt = getopt( argc, argv, optString ); }
globalArgs.inputFiles = argv + optind;
globalArgs.numInputFiles = argc - optind;
convert_document();