Monday, December 19, 2011

[C] ‘getopt()' function in Linux

先贴个网站(没错,是万恶又全能的Linux man page):
http://linux.die.net/man/3/getopt

再晒下自己代码:
/*
 * =====================================================================================
 *
 *       Filename:  argopt.c
 *
 *    Description:  Test example for 'getopt' function
 *
 *        Version:  1.0
 *        Created:  Monday, December 19, 2011 04:54:49 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Hongchao Deng (fengjingchao), fengjingchao@gmail.com
 *        Company:  Sun Yat-sen University
 *
 * =====================================================================================
 */

#include    <errno.h>
#include    <math.h> 
#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include        <unistd.h>


/*
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:  main function
 * =====================================================================================
 */
    int
main ( int argc, char *argv[] )
{
   int opt;

   while ( (opt = getopt(argc, argv, ":if:lr")) != -1 )
   {
     
      switch ( opt ) {
      case 'i':   
      case 'l':   
      case 'r':   
         printf("option: %c\n",opt);
         break;

      case 'f':
         if(optarg[0] != '-')      printf ( "filename: %s\n",optarg );
         else{
            --optind;
            printf ( "Option '-f' needs a value\n" );
         }
         break;

      case ':':   
         printf ( "Option '-%c' needs a value\n", optopt );
         break;
        
      case '?':   
         printf ( "Unknown option: %c\n", optopt );
         break;

      default:   
         break;
      }                /* -----  end switch  ----- */
   }

  
   for ( ; optind < argc; ++optind)
   {
      printf ( "argument: %s\n", argv[optind] );
   }

   return EXIT_SUCCESS;
}  /* ----------  end of function main  ---------- */

测试用例:
./argopt -i -lr -f -i -f filename -q "Hello,world"
option: i
option: l
option: r
Option '-f' needs a value
option: i
filename: filename
Unknown option: q
argument: Hello,world

好玩吧。。说说感悟:
1. 匹配出错的时候 '当前option' 放在 'optopt' 这个变量里面。
2. optind是一个个move的。。你看上面那个 '-f' 出错的时候直接 " -- optind " 解决了。
3. option有value 的话放在 'optarg' 里面.
4. getopt()的第三个参数 optstring 前面有个 "+" | "-" , 还有个什么POSIX*****之类的环境变量,无视他们。。用最基础的就行。顺便说说加了个 ‘:’(注意如果有 +-, +- 要放前面),主要是关注出错的时候是 1.没有value, 还是 2. option不识别。
5. getopt()是自动permute的,注意最后所有变量都放在 optind -- argc之间。。

getiopt_long() 是GNU扩展版。看了man page 的样例后说说感想:
1. optstring可以有数字字符,即 [0-9], 其他的不知道,也没必要知道。你看Linux命令有 '-*', '-%'这样的吗。。。
2. optarg: 如果没有 arg, optarg = 0. 这个特性可以方便编程。

No comments:

Post a Comment