C中的getopt()函数,用于解析命令行参数

getopt()函数是C语言中的一个内置函数,用于解析命令行参数。

null

语法 :

getopt(int argc, char *const argv[], const char *optstring)

optstring is simply  a list of characters, 
each representing a single character option.

返回值 :getopt()函数返回不同的值:

  • 如果该选项接受一个值,则该值是指向外部变量的指针 optarg。
  • “-1”,如果没有更多选项可处理。
  • ‘?’ 当存在无法识别的选项并将其存储到外部变量中时 optopt。
  • 如果一个选项需要一个值(比如我们的例子中的-f),但没有给出任何值,getopt通常会返回?。 通过将冒号作为选项字符串的第一个字符,getopt返回:而不是?当没有给出任何值时。

通常,getopt()函数是从循环的条件语句内部调用的。当getopt()函数返回-1时,循环终止。然后使用getopt()函数返回的值执行switch语句。

第二个循环用于处理第一个循环中无法处理的剩余额外参数。

下面的程序演示了C中的getopt()函数:

// Program to illustrate the getopt()
// function in C
#include <stdio.h>
#include <unistd.h>
int main( int argc, char *argv[])
{
int opt;
// put ':' in the starting of the
// string so that program can
//distinguish between '?' and ':'
while ((opt = getopt(argc, argv, “: if :lrx”)) != -1)
{
switch (opt)
{
case ‘i’:
case ‘l’:
case ‘r’:
printf (“option: %c”, opt);
break ;
case ‘f’:
printf (“filename: %s”, optarg);
break ;
case ‘:’:
printf (“option needs a value”);
break ;
case ‘?’:
printf (“unknown option: %c”, optopt);
break ;
}
}
// optind is for the extra arguments
// which are not parsed
for (; optind < argc; optind++){
printf (“extra arguments: %s”, argv[optind]);
}
return 0;
}


输出 : 图片[1]-C中的getopt()函数,用于解析命令行参数-yiteyi-C++库

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享