getopt函数的作用是用来对命令行输入的参数进行处理。直接看例子。
1 源代码 getopt.c
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
char optChar;
while(-1 != (optChar=getopt(argc, argv, "whn:")))
{
switch(optChar)
{
case 'w':
printf("Welcome!\n");
break;
case 'h':
printf("Hello!\n");
break;
case 'n':
printf("Hi, %s!\n", optarg);
break;
}
}
return 0;
}
2 运行结果
$ ./getopt -w
Welcome!
$ ./getopt -h
Hello!
$ ./getopt -n mjzhan
Hi, mjzhan!
$ ./getopt -hn mjzhan
Hello!
Hi, mjzhan!
3 对关键语句进行解释
optChar=getopt(argc, argv, "whn:")
3.1 getopt的输入参数
getopt有三个参数,前两个不多做解