Chinaunix首页 | 论坛 | 博客

  • 博客访问: 277386
  • 博文数量: 55
  • 博客积分: 1597
  • 博客等级: 上尉
  • 技术积分: 590
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-30 17:40
文章分类

全部博文(55)

文章存档

2016年(2)

2014年(5)

2013年(35)

2012年(5)

2010年(4)

2009年(4)

我的朋友

分类: C/C++

2012-12-20 20:06:58

1. 函数原型:
    #include
    int getopt(int argc, char * const argv[], const char *optstring);

    extern char *optarg;           /*  选项值  */
    extern int optind;                /*  下一个待处理参数的索引  */
    extern int opterr;                /*  设置为0时,不会向stderr打印错误信息 */
    extern int optopt;               /*   对于无法识别的选项,getopt()返回一个问号(?),并把它保存在optopt中 */

2.作用:
    解析命令行参数。

3.示例:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>

  4. int main(int argc, char *argv[])
  5. {
  6.     int opt = 0;
  7.     int i;
  8.      
  9.     //opterr = 0;

  10.     if (argc < 2)
  11.     {
  12.         printf("Usage : ./getopt -h hostname -p port -f filename -s\n\n");
  13.         return 0;
  14.     }

  15.     // while( (opt = getopt(argc, argv, "+h:p:f::s") ) != -1)
  16.     while( (opt = getopt(argc, argv, "h:p:f::s") ) != -1)
  17.     {
  18.         switch(opt)
  19.         {
  20.             case 'h':
  21.                 printf("parameter hostname's value is %s.\n", optarg);
  22.                 break;
  23.             case 'p':
  24.                 printf("parameter port's value is %s.\n", optarg);
  25.                 break;
  26.             case 'f':
  27.                 printf("parameter file's value is %s.\n", optarg);
  28.                 break;
  29.             case 's':
  30.                 printf("parameter is socket.\n");
  31.                 break;
  32.             default:
  33.                 printf("unknow parameter %c. getopt() return %c\n", optopt, opt);
  34.                 break;
  35.         }
  36.         printf(" optind is %d, argv[optind] = %s \n", optind, argv[optind]);
  37.     }

  38.     /* print *argv[] */
  39.     for(i = 0; i < argc; i++)
  40.     {
  41.         printf("argv[%d] = %s.\n", i, argv[i]);
  42.     }

  43.      return 0;
  44. }
gcc getopt.c -o getopt
./getopt  -h Cinderella -p 1234 -f domain.socket -s

4.说明:
  1)关于optstring  -> h:p:f::s
         a.  单个字符(例如 h)表示参数
         b.  ":" 表示参数(例如 h)后必须有一个参数值,可以是 (-h hostname)形式,也可以是(-hhostname)形式。
         c.  "::"表示参数 f 后必须有一个参数值,且只能是(-ffilename)形式,参数和参数值之间不能有空格。
  
   2)getopt会改变命令行参数的顺序
        
./getopt  -h Cinderella -p 1234 -f domain.socket -s
         因为(-f domain.socket) 中间有了一个空格,所以从输出中可以看出顺序的改变。

    3)关于'+'加号开头或者环境变量POSIXLY_CORRE被设置
         如果optstring中的字符串以'+'加号开头或者环境变量POSIXLY_CORRE被设置。
         那么一遇到不包含选项的命令行参数,getopt就会停止,返回-1。
阅读(1645) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

socay22012-12-21 13:15:31

现在多用 getopt_long 了吧,需要支持长选项!