Linux库函数之getopt理解

在Linux这类操作系统中,有大量的命令行处理程序,例如gcc -o test test.c,那么像这么多的命令行参数它是怎么去分析的呢,就要用到这里介绍的getopt函数。

getopt函数最早出现在UNIX操作系统中,因为早期与操作系统交互全是命令终端下,最后这个函数就作为了GNU C的一部分。

函数原型如下:

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

argc、argv当然是main中的argc和argv了,分别代表命令行参数个数和命令行参数列表。

要使用这个函数,需要包含头文件unistd.h。

我们看getopt.c给的一个测试实例:

int
main (argc, argv)
     int argc;
     char **argv;
{
  int c;
  int digit_optind = 0;

  while (1)
    {
      int this_option_optind = optind ? optind : 1;

      c = getopt (argc, argv, "abc:d:0123456789");
      if (c == -1)
	break;

      switch (c)
	{
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	  if (digit_optind != 0 && digit_optind != this_option_optind)
	    printf ("digits occur in two different argv-elements.\n");
	  digit_optind = this_option_optind;
	  printf ("option %c\n", c);
	  break;

	case 'a':
	  printf ("option a\n");
	  break;

	case 'b':
	  printf ("option b\n");
	  break;

	case 'c':
	  printf ("option c with value `%s'\n", optarg);
	  break;

	case '?':
	  break;

	default:
	  printf ("?? getopt returned character code 0%o ??\n", c);
	}
    }

  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
	printf ("%s ", argv[optind++]);
      printf ("\n");
    }

  exit (0);
}
我们可以将它保存在test.c中,编译测试一下,例如:

./test -a

将会打印出option a

getopt每调用一次返回一个选项,它是通过传递的optstring参数去判断的,optstring它这样一种字符串:

单个字符,字符后面接一个:(一个冒号)表示选项后面紧跟一个选项参数,字符后面接::(两个冒号)表示选项后面跟一个可选的选项参数,其中使用全局变量optarg指向这个选项参数。所以上面的例子中a就不带参数,c带一个参数。如果我们给的命令行参数在optstring中没有找到,那么getopt函数将返回一个?。

getopt函数依一次只解析一个命令行参数,所以通常需要一个循环,依次对命令行参数做解析。

还有一点需要说明的是,全局变量optind表示下一次调用getopt的索引, 初始值为1,  也就是说不会对第一个命令行参数做解析。

posted @ 2012-05-29 15:41  移动应用开发  阅读(226)  评论(0编辑  收藏  举报