作用
getopt()用来分析命令行参数。参数argc和argv分别代表参数个数和内容,跟main()函数的命令行参数是一样的。
//头文件
#include <unistd.h>
//函数原型
int getopt(int argc, char * const argv[], const char *optstring);
参数说明
- argc:就是main函数的形参argc,表示参数的数量
- argv:就是main函数的形参argv,表示参数的字符串变量数组
- optstring:选项字符串,一个字母表示不带值的参数,如果字母后带有一个
:
,表示必须带值的参数。如果带有两个:
,表示是可选的参数。
例如"ab:c::“,程序运行时可接受的参数为”-a -b 1 -c"或者"-a -b 1 -c2"
- 多个不带值的参数可以进行连写
- 可选值的参数,中间不可以带有空格
返回值说明:
- optarg:用于获取传入的参数的值。
- optind:argv 的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字符串视为操作数,在argv[optind]至argv[argc-1]中可以找到
- opterr:正常运行状态下为 0。非零时表示存在无效选项或者缺少选项参数,并输出其错误信息
- optopt:当发现无效选项字符之时,getopt()函数或返回’?‘字符,或返回’:'字符,并且optopt包含了所发现的无效选项字符
使用方法
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int para;
while ((para = getopt(argc, argv, "ab:c::")) != -1) {
switch (para) {
case 'a':
printf("参数是a,无值\n");
break;
case 'b':
printf("参数是b, 值是: %s\n", optarg);
break;
case 'c':
if(optarg)
printf("参数是c, 值是: %s\n", optarg);
else
printf("参数是c,无值\n");
break;
default:
printf("error opterr: %d\n", opterr);
break;
}
}
return 0;
}