1、定义:
int getopt(int argc, char * const argv[], const char *optstring);
2、描述:
getopt是用来解析命令行选项参数的,但是只能解析短选项: -d 100,不能解析长选项:--prefix
3、参数:
argc:main()函数传递过来的参数的个数argv:main()函数传递过来的参数的字符串指针数组optstring:选项字符串,告知 getopt()可以处理哪个选项以及哪个选项需要参数
4、返回:
如果选项成功找到,返回选项字母;如果所有命令行选项都解析完毕,返回 -1;如果遇到选项字符不在 optstring 中,返回字符 '?';如果遇到丢失参数,那么返回值依赖于 optstring 中第一个字符,如果第一个字符是 ':' 则返回':',否则返回'?'并提示出错误信息。
5、下边重点举例说明optstring的格式意义:
char*optstring = “ab:c::”;单个字符a 表示选项a没有参数 格式:-a即可,不加参数单字符加冒号b:表示选项b有且必须加参数格式:-b 100或-b100,但-b=100错单字符加2冒号c:: 表示选项c可以有,也可以无格式:-c200,其它格式错误
上面这个 optstring 在传入之后,getopt 函数将依次检查命令行是否指定了 -a, -b, -c(这需要多次调用 getopt 函数,直到其返回-1),当检查到上面某一个参数被指定时,函数会返回被指定的参数名称(即该字母)
optarg —— 指向当前选项参数(如果有)的指针。optind —— 再次调用 getopt() 时的下一个 argv指针的索引。optopt —— 最后一个未知选项。opterr —— 如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
以上描述的并不生动,下边结合实例来理解:
6、实例:
#include<stdio.h>#include<unistd.h>#include<getopt.h>int main(intargc, char *argv[]){int opt;char *string = "a::b:c:d";while ((opt = getopt(argc, argv, string))!= -1){ printf("opt = %c\t\t", opt);printf("optarg = %s\t\t",optarg);printf("optind = %d\t\t",optind);printf("argv[optind] = %s\n",argv[optind]);} }
编译上述程序并执行结果:
输入选项及参数正确的情况
dzlab:~/test/test#./opt -a100 -b 200 -c 300 -dopt = a optarg = 100 optind = 2 argv[optind] = -bopt = b optarg = 200 optind = 4 argv[optind] = -copt = c optarg = 300 optind = 6 argv[optind] = -dopt = d optarg = (null) optind = 7 argv[optind] = (null)
或者这样的选项格式(注意区别):
dzlab:~/test/test#./opt -a100 -b200 -c300 -d opt = a optarg = 100 optind = 2 argv[optind] = -b200opt = b optarg = 200 optind = 3 argv[optind] = -c300opt = c optarg = 300 optind = 4 argv[optind] = -dopt = d optarg = (null) optind = 5 argv[optind] = (null)
选项a是可选参数,这里不带参数也是正确的
dzlab:~/test/test#./opt -a -b 200 -c 300 -d opt = a optarg = (null) optind = 2 argv[optind] = -bopt = b optarg = 200 optind = 4 argv[optind] = -copt = c optarg = 300 optind = 6 argv[optind] = -dopt = d optarg = (null) optind = 7 argv[optind] = (null)
输入选项参数错误的情况
dzlab:~/test/test#./opt -a 100 -b 200 -c 300 -dopt = a optarg = (null) optind = 2 argv[optind] = 100opt = b optarg = 200 optind = 5 argv[optind] = -copt = c optarg = 300 optind = 7 argv[optind] = -dopt = d optarg = (null) optind = 8 argv[optind] = (null)
导致解析错误,第一个 optarg = null,实际输入参数 100,由于格式不正确造成的(可选参数格式固定)
参数丢失,也会导致错误,c选项是必须有参数的,不加参数提示错误如下:
dzlab:~/test/test#./opt -a -b 200 -copt = a optarg = (null) optind = 2 argv[optind] = -bopt = b optarg = 200 optind = 4 argv[optind] = -c./opt: optionrequires an argument -- 'c'opt = ? optarg = (null) optind = 5 argv[optind] = (null)
这种情况,optstring 中第一个字母不是':',如果在 optstring 中第一个字母加':',则最后丢失参数的那个选项 opt 返回的是':',不是'?',并且没有提示错误信息,这里不再列出。
命令行选项未定义,-e选项未在optstring中定义,会报错:
dzlab:~/test/test#./opt -a -b 200 -eopt = a optarg = (null) optind = 2 argv[optind] = -bopt = b optarg = 200 optind = 4 argv[optind] = -e./opt: invalidoption -- 'e'opt = ? optarg = (null) optind = 5 argv[optind] = (null)