Chinaunix首页 | 论坛 | 博客
  • 博客访问: 68674
  • 博文数量: 32
  • 博客积分: 2024
  • 博客等级: 大尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-16 15:05
文章分类

全部博文(32)

文章存档

2009年(32)

我的朋友
最近访客

分类: LINUX

2009-03-24 12:53:37

原型:

#include <unistd.h>

int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;

参数argc、argv分别对应main函数的参数,表示参数个数和参数数组,opstring是预处理的选项字符串。

getopt函数调用会返回第一个选项,如果以相同的参数再次调用的话会返回下一个选项,以此类推,当参数列已经到结尾时getopt返回-1,当遇到一个未知的选项时getopt返回'?',并且每次都会重新设置相应的全局变量。

getopt的全局变量包括:

  1. optarg(char *)--指向当前选项参数的指针;
  2. optind(int)--再次调用getopt时的下一个argv指针的索引;
  3. optopt(int)--最后一次调用getopt()返回的已知项;
  4. opterr(int)--变量opterr被初始化为1。如果不希望getopt()输出出错信息,将全域变量opterr设为0即可。

例子:

 

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char **argv)
{
    int ch;
    opterr = 0;
    while((ch = getopt(argc, argv, "a:bcde"))!= -1){
         switch(ch){
         case 'a':
              printf("option a: %s\n", optarg);
              break;
         case 'b':
              printf("option b: b\n");
              break;
         default:
              printf("other option: %c\n", ch);
              break;
         }

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

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