一個簡單的GNU getopt函數的測試例子

來源:互聯網
上載者:User

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

 * 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.