涉及到名词:命令+选项+选项参数+操作数
# cat -n 10 /etc /passwd
cat是命令名,-n是选项,10是选项参数,/etc/passwd是操作数。
函数原型:
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
opterr,默认是非零1,如果调用出错时看opterr的值,如果非零就打印错误信息。若果是0就不打印。所以可以在调用前设置opterr=0,抑制getopt内部的错误信息的输出。
optopt,当调用选项在optstring中没有时,opt存放该invalid选项;另外,要是optstring字串中后面接冒号的需要选项参数的选项在调用时没有选项参数,则optopt保存该missing argument的选项。
optarg,当选项需要选项参数时,选项参数会保存在optarg中。
optind,index 下标值,本次调用后argv数组中第一个非选项(包含选项参数)的下标值。
返回值:
1、 正常情况返回解析出来的选项字符,optstring解析完后返回-1。
2、 Invalid参数返回’?’。
3、 Missing argument返回依赖于optstring字串的首字符是否为冒号,如果是冒号则返回冒号,否则返回’?’。
为了便于区分是invalid还是missing argument,建议optstring以冒号开头。
例程:
#include <stdio.h>
#include <getopt.h>
int main(int argc, char **argv)
{
char result;
//opterr = 0;
while(-1 != (result = getopt(argc, argv, ":ln:q:m:")))
{
switch(result)
{
case 'l':
printf("This option is 'l'\n");
break;
case 'n':
printf("This option is 'n' which need argument %s\n", optarg);
break;
case 'q':
printf("This option is 'q' which need argument %s\n", optarg);
break;
case 'm':
printf("This option is 'm' which need argument %s\n", optarg);
break;
case '?':
printf("Optioin '%c' is a unknown argument\n", (char)optopt);
break;
case ':':
printf("Option '%c' missing a argument\n", (char)optopt);
break;
default:
break;
}
}
return 0;
}
运行结果:
[root@localhost test]# ./a.out -n
Option 'n' missing a argument
[root@localhost test]# ./a.out -m
Option 'm' missing a argument
[root@localhost test]# ./a.out -l
This option is 'l'