#include <srdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int ch;
while((ch = getopt(argc, argv, "ab:c::d")) != -1){
switch(ch){
case 'a':
print("a, no opt");
break;
case 'b':
print("b, opt:", optarg);
break;
case 'c':
print("c, opt:", optarg);
break;
case 'd':
print("d, no opt");
break;
default:
print("opt err");
}
}
return 0;
}
输出:
./a.out -a x
a, no opt
./a.out -a -b x
a, no opt
b, opt: x
./a.out -ab x -c xx
a, no opt
b, opt: x
c, opt: //xx应紧跟c后面
./a.out -adb x -cxx
a, no opt
d, no opt
b, opt: x
c, opt: xx
Linux中getopt函数、optind等变量使用详解
1. getopt函数的声明
该函数是由Unix标准库提供的函数,查看命令man 3 getopt
#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
getopt函数的参数:
- 参数argc和argv:通常是从main的参数直接传递而来,argc是参数的数量,argv是一个常量字符串数组的地址。
- 参数optstring:一个包含正确选项字符的字符串,如果一个字符后面有冒号,那么这个选项在传递参数时就需要跟着一个参数。
外部变量:
- char *optarg:如果有参数,则包含当前选项参数字符串
- int optind:argv的当前索引值。当getopt函数在while循环中使用时,剩下的字符串为操作数,下标从optind到argc-1。
- int opterr:这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
- int optopt:当发现无效选项字符之时,getopt()函数或返回 \’ ? \’ 字符,或返回字符 \’ : \’ ,并且optopt包含了所发现的无效选项字符。