int getopt(int argc,char * const argv[ ],const char * optstring);
其中:
argc,argv[]可直接从main函数获取,不解释。
optstring为"abc:d"形式,其中'a','b','c','d'表示可解析的参数,'c'后面的':'表示option 'c'后面需跟一个值。
int getopt_long(int argc, char * const argv[],const char *optstring,const struct option*longopts,int *longindex);
其中:
前三个参数同上。
longopts为结构体指针,它有如下的形式:
{ “help”, 0, NULL, ‘h’ },表示长参数为 "help",不需要值,第三个参数总是NULL,第四个'h'表示短参数。
{ “name”, 1, NULL, ‘n’ },表示长参数为"name",后面需跟值,第三个参数总是NULL,第四个'n'表示短参数。
getopt() 所设置的全局变量包括:
optarg——指向当前选项参数(如果有)的指针。 optind——再次调用 getopt() 时的下一个 argv 指针的索引。 optopt——最后一个未知选项。
getopt使用如下:
#include
#include
int main(int argc,char **argv)
{
int ch;
while((ch = getopt(argc,argv,"a:b"))!= -1)
{
switch(ch)
{
case 'a':
printf("option a:’%s’\n",optarg);
break;
case 'b':
printf("option b :b\n");
break;
case -1:
printf("handle option done\n");
break;
case '?':
printf("invalid option\n");
break;
default:
printf("other option :%c\n",ch);
}
printf("optopt +%c\n",optopt);
}
}
编译:
gcc getopt.c
使用:
./a.out -a abc
输出:
option a:’abc
optopt +?
getopt_long使用如下:
#include
#include
char *l_opt_arg;
char* const short_options = "nbl:";
struct option long_options[] = {
{ "name", 0, NULL, 'n' },
{ "bf_name", 0, NULL, 'b' },
{ "love", 1, NULL, 'l' },
{ 0, 0, 0, 0},
};
int main(int argc, char *argv[])
{
int c;
while((c = getopt_long (argc, argv, short_options, long_options, NULL)) != -1)
{
switch (c)
{
case 'n':
printf("My name is XL.\n");
break;
case 'b':
printf("His name is ST.\n");
break;
case 'l':
l_opt_arg = optarg;
printf("Our love is %s!\n", l_opt_arg);
break;
}
}
return 0;
}
编译:
gcc getopt_long.c
使用:
$ ./a.exe -n -l nick
输出:
My name is XL.
Our love is nick!
参考:
http://baike.baidu.com/view/906700.htm
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch02-writing-good-gnu-linux-software.pdf