参数解析:getopt
getopt可以获取短参数(-a -b -c),其包含在unistd.h中。
函数:
int getopt (int argc, char *const *argv, const char *options)
变量:int opterr
如果此变量的值非零,则如果getopt遇到未知的选项字符或缺少必需参数的选项,则将错误消息输出到标准错误流。
这是默认行为。如果将此变量设置为零,则getopt不会输出任何消息,但仍会返回字符?表示错误。
变量:int optopt
当getopt遇到未知的选项字符或缺少必需参数的选项时,它将在该变量中存储该选项字符。您可以使用它来提供自己的诊断消息。
变量:int optind
该变量由getopt设置为要处理的argv数组下一个元素的索引。一旦getopt找到所有选项参数,就可以使用此变量来确定其余非选项参数的开始位置。该变量的初始值为1。
变量:char * optarg
对于接受参数的那些选项,由getopt将该变量设置为指向选项参数的值。
- 通常,getopt是在循环中调用的。 当getopt返回-1(指示不再存在任何选项)时,循环终止。
- switch语句用于调度getopt的返回值。 在典型的用法中,每种情况仅设置一个变量,该变量将在程序的后面使用。
- 第二个循环用于处理其余的非选项参数。
全部代码:
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { int aflag = 0; int bflag = 0; char *cvalue = NULL; int index; int c; opterr = 0; while ((c = getopt(argc, argv, "abc:")) != -1) switch (c) { case 'a': aflag = 1; break; case 'b': bflag = 1; break; case 'c': cvalue = optarg; break; case '?': if (optopt == 'c') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort(); } printf("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue); for (index = optind; index < argc; index++) printf("Non-option argument %s\n", argv[index]); return 0; } /* Here are some examples showing what this program prints with different combinations of arguments: % testopt aflag = 0, bflag = 0, cvalue = (null) % testopt -a -b aflag = 1, bflag = 1, cvalue = (null) % testopt -ab aflag = 1, bflag = 1, cvalue = (null) % testopt -c foo aflag = 0, bflag = 0, cvalue = foo % testopt -cfoo aflag = 0, bflag = 0, cvalue = foo % testopt arg1 aflag = 0, bflag = 0, cvalue = (null) Non-option argument arg1 % testopt -a arg1 aflag = 1, bflag = 0, cvalue = (null) Non-option argument arg1 % testopt -c foo arg1 aflag = 0, bflag = 0, cvalue = foo Non-option argument arg1 % testopt -a -- -b aflag = 1, bflag = 0, cvalue = (null) Non-option argument -b % testopt -a - aflag = 1, bflag = 0, cvalue = (null) Non-option argument - */