`
fp_moon
  • 浏览: 971441 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

getopt详解

 
阅读更多

getopt被用来解析命令行选项参数。就不用自己写东东处理argv了。

#include <unistd.h>
       extern char *optarg;  //选项的参数指针
       extern int optind,   //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
       extern int opterr,  //当opterr=0时,getopt不向stderr输出错误信息。
       extern int optopt;  //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回'?’、
       int getopt(int argc, char * const argv[], const char *optstring);
调用一次,返回一个选项。 在命令行选项参数再也检查不到optstring中包含的选项时,返回-1,同时optind储存第一个不包含选项的命令行参数。


首先说一下什么是选项,什么是参数。
字符串optstring可以是下列元素:


1.单个字符,表示选项;
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。

getopt处理以'-’开头的命令行参数,如optstring="ab:c::d::",命令行为getopt.exe -a -b host -ckeke -d haha
在这个命令行参数中,-a,-b,-c和-d就是选项元素,去掉'-',a,b,c,d就是选项。host是b的参数,keke是c的参数。但haha并不是d的参数,因为它们中间有空格隔开。
还要注意的是默认情况下getopt会重新排列命令行参数的顺序,所以到最后所有不包含选项的命令行参数都排到最后。
如:getopt.exe -a ima -b host -ckeke -d haha, 到最后命令行参数的顺序是: -a -b host -ckeke -d ima haha

如果optstring中的字符串以'+'加号开头或者环境变量POSIXLY_CORRE被设置。那么一遇到不包含选项的命令行参数,getopt就会停止,返回-1。

[cpp] view plaincopyprint?
01.#include <stdio.h>  
02.#include <stdlib.h>  
03.#include <unistd.h>  
04.int main(int argc, char **argv) 
05.{ 
06.    int result; 
07.    opterr = 0;  //使getopt不行stderr输出错误信息  
08.    while( (result = getopt(argc, argv, "ab:c::")) != -1 ) 
09.    { 
10.           switch(result) 
11.          { 
12.               case 'a': 
13.                   printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg); 
14.                   break; 
15.              case 'b': 
16.                   printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg); 
17.                   break; 
18.              case 'c': 
19.                   printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg); 
20.                   break; 
21.              case '?': 
22.                    printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg); 
23.                    break; 
24.              default: 
25.                   printf("default, result=%c\n",result); 
26.                   break; 
27.           } 
28.        printf("argv[%d]=%s\n", optind, argv[optind]); 
29.    } 
30.    printf("result=-1, optind=%d\n", optind);   //看看最后optind的位置  
31.    for(result = optind; result < argc; result++) 
32.         printf("-----argv[%d]=%s\n", result, argv[result]); 
33. //看看最后的命令行参数,看顺序是否改变了哈。  
34.    for(result = 1; result < argc; result++) 
35.          printf("\nat the end-----argv[%d]=%s\n", result, argv[result]); 
36.    return 0; 
37.} 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    int result;
    opterr = 0;  //使getopt不行stderr输出错误信息
    while( (result = getopt(argc, argv, "ab:c::")) != -1 )
    {
           switch(result)
          {
               case 'a':
                   printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'b':
                   printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'c':
                   printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case '?':
                    printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
              default:
                   printf("default, result=%c\n",result);
                   break;
           }
        printf("argv[%d]=%s\n", optind, argv[optind]);
    }
    printf("result=-1, optind=%d\n", optind);   //看看最后optind的位置
    for(result = optind; result < argc; result++)
         printf("-----argv[%d]=%s\n", result, argv[result]);
 //看看最后的命令行参数,看顺序是否改变了哈。
    for(result = 1; result < argc; result++)
          printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);
    return 0;
}


unistd里有个optind变量,每次getopt后,这个索引指向argv里当前分析的字符串的下一个索引;

因此argv[optind]就能得到下个字符串,通过判断是否以 '-'开头就可。

下面是个测试程序:

[cpp] view plaincopyprint?
01.#include <stdio.h>  
02.#include <unistd.h>  
03.int main(int argc, char* argv[]) 
04.{ 
05.    int tmp = 4; 
06.     
07.    while( (tmp = getopt(argc, argv, "abck")) != -1  ) 
08.    { 
09.            
10.           printf("-%c\t", tmp); 
11.           int opt = optind ; 
12.           while( opt < argc ) 
13.           { 
14.                  if ( argv[opt][0] != '-' ) 
15.                  { 
16.                       printf("%s\t", argv[opt]); 
17.                       opt ++; 
18.                  } 
19.                  else 
20.                      break; 
21.           } 
22.           printf("\n"); 
23.    } 
24.    getchar(); 
25.} 
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
    int tmp = 4;
   
    while( (tmp = getopt(argc, argv, "abck")) != -1  )
    {
          
           printf("-%c\t", tmp);
           int opt = optind ;
           while( opt < argc )
           {
                  if ( argv[opt][0] != '-' )
                  {
                       printf("%s\t", argv[opt]);
                       opt ++;
                  }
                  else
                      break;
           }
           printf("\n");
    }
    getchar();
}
函数说明:

getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。
返回值  如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1。

范例:

[cpp] view plaincopyprint?
01.#include<stdio.h>  
02.#include<unistd.h>  
03.int main(int argc,char **argv) 
04.{ 
05.int ch; 
06.opterr = 0; 
07.while((ch = getopt(argc,argv,”a:bcde”))!= -1) 
08.switch(ch) 
09.{ 
10.case ‘a’: 
11.printf(“option a:’%s’\n”,optarg); 
12.break; 
13.case ‘b’: 
14.printf(“option b :b\n”); 
15.break; 
16.default: 
17.printf(“other option :%c\n”,ch); 
18.} 
19.printf(“optopt +%c\n”,optopt); 
20.} 
#include<stdio.h>
#include<unistd.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);
}
printf(“optopt +%c\n”,optopt);
}
执行  $./getopt –b

option b:b
$./getopt –c
other option:c
$./getopt –a
other option :?
$./getopt –a12345
option a:’12345’


原文连接:http://www.diybl.com/course/3_program/c++/cppjs/20091031/180765.html

http://qxinli.com/post/2012-05-30/40028624644

分享到:
评论

相关推荐

    Linux库函数getopt详解,有相关的源码测试结果,简单一看就懂。

    1、Linux库函数getopt详解,把getopt的常用相关参数都有说明。 2、有相关的源码测试结果,简单一看就懂。 3、无需自己写代码测试,直接把图片测试结果和描述写在了文档中。 4、希望能帮到你。

    python getopt详解及简单实例

    python getopt详解 函数原型: getopt.getopt(args, shortopts, longopts=[]) 参数解释: args:args为需要解析的参数列表。一般使用sys.argv[1:],这样可以过滤掉第一个参数(ps:第一个参数是脚本的名称,它不...

    命令行解析函数getopt用法详解

    命令行解析函数getopt使用方法详解,更方便分析命令参数

    getopt命令 解析命令行选项

    getopt命令用于解析命令行选项,检测给定的选项是否合法。在此命令中,选项部分主要用于影响getopt命令解析选项,其中optstring是需要解析的合法选项的字符串,paramenters通常是一组变量,用于存储从命令行获取的每...

    getopt函数详解

    详细地介绍了getopt命令行处理函数的用法。

    Python中的getopt函数使用详解

    主要介绍了Python中的getopt函数使用详解,是Python进阶学习中的重要知识,需要的朋友可以参考下

    python通过getopt模块如何获取执行的命令参数详解

    前言 python脚本和shell脚本一样可以获取命令行的参数,根据不同的参数,执行不同的逻辑处理。 通常我们可以通过getopt模块获得不同的执行命令和参数。... opts, args = getopt.getopt(sys.argv[1:], ht:q:,

    python模块详解

    python模块详解 各个模块的详解 核心模块 1.1. 介绍 1.2. _ _builtin_ _ 模块 1.3. exceptions 模块 1.4. os 模块 1.5. os.path 模块 1.6. stat 模块 1.7. string 模块 1.8. re 模块 1.9. math 模块 1.10....

    Python命令行解析模块详解

    本文研究的主要是Python命令行解析...这个模块提供两个函数(getopt.getopt()/getopt.gnu_getopt())和一个参数异常(getopt.GetoptError)。 这里重点介绍getopt.getopt()这个函数。 函数原型:getopt.getopt(args,

    TCP-IP详解-卷2实现分两部分-part2

    8.8.2 PRCO_GETOPT的处理 193 8.9 ip_sysctl函数 193 8.10 小结 194 第9章 IP选项处理 196 9.1 引言 196 9.2 代码介绍 196 9.2.1 全局变量 196 9.2.2 统计量 197 9.3 选项格式 197 9.4 ip_dooptions函数 198 9.5 ...

    python解析命令行参数的三种方法详解

    这篇文章主要介绍了python解析命令行参数的三种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 python解析命令行参数主要有三种方法:sys.argv、...

    TCP-IP详解卷2_2.rar

    8.8.2 PRCO_GETOPT的处理 193 8.9 ip_sysctl函数 193 8.10 小结 194 第9章 IP选项处理 196 9.1 引言 196 9.2 代码介绍 196 9.2.1 全局变量 196 9.2.2 统计量 197 9.3 选项格式 197 9.4 ip_dooptions函数 198 9.5 ...

    TCP_IP详解卷1

    《TCP/IP详解,卷1:协议》是一本完整而详细的TCP/IP协议指南。描述了属于每一层的各个协议以及它们如何在不同操作系统中运行。作者用Lawrence Berkeley实验室的tcpdump程序来捕获不同操作系统和TCP/IP实现之间传输...

    TCP-IP详解卷二:实现

    8.8.2 PRCO_GETOPT的处理 8.9 ip_sysctl函数 8.10 小结 第9章 IP选项处理 9.1 引言 9.2 代码介绍 9.2.1 全局变量 9.2.2 统计量 9.3 选项格式 9.4 ip_dooptions函数 9.5 记录路由选项 9.6 源站和记录路由选项 9.6.1 ...

    TCP/IP详解part_2

    《TCP/IP详解,卷1:协议》是一本完整而详细的TCP/IP协议指南。描述了属于每一层的各个协议以及它们如何在不同操作系统中运行。作者用Lawrence Berkeley实验室的tcpdump程序来捕获不同操作系统和TCP/IP实现之间传输...

    TCPIP协议详解卷2:实现

    8.8.2 PRCO_GETOPT的处理 193 8.9 ip_sysctl函数 193 8.10 小结 194 第9章 IP选项处理 196 9.1 引言 196 9.2 代码介绍 196 9.2.1 全局变量 196 9.2.2 统计量 197 9.3 选项格式 197 9.4 ip_dooptions函数 198 9.5 ...

    TCP-IP详解卷2:实现

    8.8.2 PRCO_GETOPT的处理 193 8.9 ip_sysctl函数 193 8.10 小结 194 第9章 IP选项处理 196 9.1 引言 196 9.2 代码介绍 196 9.2.1 全局变量 196 9.2.2 统计量 197 9.3 选项格式 197 9.4 ip_dooptions函数 198 9.5 ...

Global site tag (gtag.js) - Google Analytics