当我们使用linux系统下很多的命令时,会发现每个命令基本上都有很多的参数选项,这些参数提供给我们很多方便的功能。我们在设计自己的程序时,通常页可以加入类似的功能,我们可以使用标准c库中的getopt函数来实现。
void version()
{
printf("Version: xx 1.0.\n");
return;
}
void usage(char *pro)
{
printf("Usage:%s [Options]\n"
"Options:\n"
" -h\t: help\n"
" -v\t: version\n",pro
);
}
int main(int argc, char **argv)
{
char ch;
while((ch=getopt(argc, (char* const*)argv, "vh")) != -1)
{
switch(ch){
case 'v':
version();
break;
case 'h':
case '?':
case 'default':
usage(argv[0]);
}
}
}
其中,getopt的函数原型是:
int getopt(int argc, char *const argv[], const char *optstring);
optstring时参数选项集合,其中的每个字符代表我们提供的参数选项,如果某个字符后面有冒号,代表它后面带有参数,每次调用getopt,函数将返回一个选项,如果返回-1表示选项返回完毕。如果我们输入了一个不支持的字符,或者缺少参数,getopt返回?。
来源:https://www.cnblogs.com/canyudeguang/p/6853526.html