Linux getopt调用

  
一、函数原型

           #include    <unistd.h>

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

       extern   char  *optarg;

       extern    int  optind, opterr,  optopt;

1、函数说明

       getopt()函数将传递给程序main函数的argc和argv作为参数,同时接受一个选项指定符字符串optstring,该字符串告诉getopt()哪些选项可用,以及它们是否还有相关的参数。optstring只是一个字符列表,每个字符代表一个单字符选项。

2、返回值

       getopt()每次调用会逐次返回命令行传入的参数。

       如果选项处理完毕,getopt()将返回-1。

       当解析到一个不在optstring里面的参数,或者一个必选值参数不带值时,返回'?'。

       当optstring是以':'开头时,缺值参数的情况下会返回':',而不是'?' 。      

3、全局变量说明

optind:被设置为下一个待处理参数的索引。当所有选项参数都处理完毕时,optind将指向argv数组尾部可以找到其余参数的位置。

       有些版本的getopt()会在第一个非选项参数处停下来,返回-1并设置optind的值。而在linux提供的版本中,getopt能够处理出现在程序参数中任意位置的选项,实际上getopt()实际上重写了argv数组,把所有非选项参数都集中在一起,从argv[optind]位置开始。

optopt:保存最后一个由 getopt() 返回的已知的选项。

opterr:如果opterr非零,当遇到未声明的选项字符或者选项字符后面缺失了参数,则打印错误消息到标准错误流。这是缺省的行为。如果设置opterr为零,则不会打印错误消息。

 

二、短参数的定义

       getopt()使用optstring所指的字串作为短参数列表,象"1ac:d::"就是一个短参数列表。短参数的定义是一个'-'后面跟一个字母或数字,像-a就是一个短参数。每个数字或字母定义一个参数。其中短参数在getopt定义里分为三种:

       1、不带值的参数,它的定义即是参数本身。

       2、必须带值的参数,它的定义是在参数本身后面再加一个冒号。

       3、可选值的参数,它的定义是在参数本身后面加两个冒号 。

       在上例中,1,a就是不带值的参数,c是必须带值的参数,d是可选值的参数。

       在实际调用中有两点注意:

       1、不带值的参数可以连写,例如1和a是不带值的参数,它们可以-1 -a分开写,也可以-1a或-a1连写

       2、要注意可选值的参数的值与参数之间不能有空格,必须写成-ddvalue这样的格式,如果写成-d dvalue这样的格式就会解析错误。必须带值得参数的值与参数之间可以没有空格,也可以有空格。

 

三、范例

#include <stdio.h>  
#include <unistd.h>  
int main(int argc, int *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);
}

执行结果:

$ ./getopt -a  
other option :?
optopt +a  

$ ./getopt -b  
option b :b  
optopt +  

$ ./getopt -c  
other option :c  
optopt +  

$ ./getopt -d  
other option :d  
optopt +  

$ ./getopt -abcd  
option a:'bcd' 
optopt +  

$ ./getopt -bcd  
option b :b  
other option :c  
other option :d  
optopt +  

$ ./getopt -bcde  
option b :b  
other option :c  
other option :d  
other option :e  
optopt +  

$ ./getopt -bcdef  
option b :b  
other option :c  
other option :d  
other option :e  
other option :?  
optopt +f  


 

 

 

     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值