Chinaunix首页 | 论坛 | 博客
  • 博客访问: 286998
  • 博文数量: 70
  • 博客积分: 485
  • 博客等级: 下士
  • 技术积分: 632
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-25 08:55
文章分类

全部博文(70)

文章存档

2014年(47)

2013年(1)

2012年(22)

我的朋友

分类: C/C++

2014-04-23 09:57:50

getopt用来解析命令行选项参数
头文件:#include
函数定义: int getopt(int argc,char * const argv[ ],const char * optstring);
函数说明:参数argc和argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。
       extern char *optarg;  //选项的参数指针
      extern int optind,   //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。 
      extern int opterr,  //当opterr=0时,getopt不向stderr输出错误信息。
      extern int optopt;  //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt 中,getopt返回'?’、

点击(此处)折叠或打开

  1. int main(int argc, char *argv[])
  2. {
  3.       int ch;
  4.       opterr = 0;
  5.        while ((ch = getopt(argc, argv, "a:bcde"))!=-1)
  6.        {
  7.           switch(ch)
  8.           {
  9.               case 'a':
  10.                   printf("option a:[%s]\n", optarg);
  11.                   break;
  12.               case 'b':
  13.                   printf("option b:[b]\n");
  14.                   break;
  15.               default:
  16.                   printf("other option:%c\n",ch);
  17.           }
  18.       }
  19.       printf("optopt+%c\n",optopt);
  20.  }


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