一个简单的GNU getopt函数的测试例子


/********************************************************

 * Function: Test getopt
 * Author  : Samson
 * Date    : 11/30/2011
 * Test platform:
 *               GNU Linux version 2.6.29.4
 *               gcc version 4.4.0 20090506 (Red Hat 4.4.0-4) (GCC)
 * ********************************************************/

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
   int flags, opt;
   int nsecs, tfnd;

   nsecs = 0;
   tfnd = 0;
   flags = 0;

   while ((opt = getopt(argc, argv, "n:t:c")) != -1)
   {
       switch (opt)
       {
        case 'n':
               flags = 1;
            printf("case n optarg is %s \n", optarg);
               break;
          case 't':
              nsecs = atoi(optarg);
            printf("case t optarg is %s \n", optarg);
               tfnd = 1;
               break;
          case 'c':
            printf("cast c is there\n");
            break;
          default: /* '?' */
            fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
               argv[0]);
               exit(EXIT_FAILURE);
       }
   }
   printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);

   if (optind >= argc)
   {
       fprintf(stderr, "Expected argument after options\n");
       exit(EXIT_FAILURE);
   }

   printf("name argument = %s\n", argv[optind]);
  
   //printf parameter Reorder by getopt
   for (opt = 0; opt < argc; opt++)
   {
       printf("argv[%d] is %s\n", opt, argv[opt]);    
   }

   /* Other code omitted */

   exit(EXIT_SUCCESS);
}

如上测试程序,当使用getopt后是会对参数列表按照getopt函数中的第三个参数规则来排序的,如测试中的"n:t:c"表示,参数应该是-n 参数 -t 参数 -c 无参数,若测试运行时输入:./a.out -c hahah -t 23 -n yygy ,而经getopt排序后的为./a.out -c -t 23 -n yygy hahah,程序测试输出为:

cast c is there
case t optarg is 23
case n optarg is yygy
flags=1; tfnd=1; optind=6
name argument = hahah
argv[0] is ./a.out
argv[1] is -c
argv[2] is -t
argv[3] is 23
argv[4] is -n
argv[5] is yygy
argv[6] is hahah

相关内容