歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

一個簡單的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

Copyright © Linux教程網 All Rights Reserved