Chinaunix首页 | 论坛 | 博客
  • 博客访问: 313919
  • 博文数量: 243
  • 博客积分: 86
  • 博客等级: 民兵
  • 技术积分: 1045
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-09 17:03
个人简介

稳重,成熟

文章分类

全部博文(243)

文章存档

2015年(2)

2013年(72)

2012年(169)

我的朋友

分类: C/C++

2013-03-19 10:35:59

原文地址:getopt函数应用 作者:asteriskchina

在执行可执行文件时,常需要加上一些参数,以便程序的执行可以按照参数的选项进行。
这时就需要用到getopt函数了。

函数原型:

int getopt(int argc, char * const argv[], const char *optstring);       

 optarg和optind是两个最重要的external 变量。optarg是指向参数的指针(当然这只针对有参数的选项);optind是argv[]数组的索引,众所周知,argv[0]是函数名称,所有参 数从argv[1]开始,所以optind被初始化设置指为1。        

每调用一次getopt()函数,返回一个选项,假如该选项有参数,则optarg指向该参数。 在命令行选项参数再也检查不到optstring中包含的选项时,返回-1。

函数getopt()有三个参数,argc和argv[]应该不需要多说,下面说一下字符串optstring,它是作为选项的字符串的列表。
 函数getopt()认为optstring中,以'-’开头的字符(不是字符串!!)就是命令行参数选项,有的参数选项后面可以跟参数值。optstring中的格式规范如下:
1) 单个字符,表示选项,
2) 单个字符后接一个冒号”:”,表示该选项后必须跟一个参数值。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3) 单个字符后跟两个冒号”::”,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。


示例:

#include

#include


int main(int argc,char *argv[])

{

  int ch;

  opterr=0;


  while((ch=getopt(argc,argv,"a:b::cde"))!=-1)

  {

    printf("optind:%d\n",optind);

    printf("optarg:%s\n",optarg);

    printf("ch:%c\n",ch);

    switch(ch)

    {

      case 'a':

        printf("option a:'%s'\n",optarg);

        break;

      case 'b':

        printf("option b:'%s'\n",optarg);

        break;

      case 'c':

        printf("option c\n");

        break;

      case 'd':

        printf("option d\n");

        break;

      case 'e':

        printf("option e\n");

        break;

      default:

        printf("other option:%c\n",ch);

    }

    printf("optopt+%c\n",optopt);

  }


}

./getopt -a 2323 -b rer -c -d

结果:

optind:3

optarg:2323

ch:a

option a:'2323'

optopt+

optind:4

optarg:(null)

ch:b

option b:'(null)'   //b 后带的参数不能用空格隔开

optopt+

optind:6

optarg:(null)

ch:c

option c

optopt+

optind:7

optarg:(null)

ch:d

option d

optopt+



阅读(215) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~