Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1589406
  • 博文数量: 695
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4027
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-20 21:22
文章分类

全部博文(695)

文章存档

2018年(18)

2017年(74)

2016年(170)

2015年(102)

2014年(276)

2013年(55)

分类: LINUX

2013-12-18 10:15:48

getopt(分析命令行参数)  
 
相关函数表头文件
        #include
定义函数
        int getopt(int argc,char * const argv[ ],const char * optstring);
函数说明
        getopt()用来分析命令行参数。参数argc和 argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错 信息,则只要将全域变量opterr设为0即可。
 
短参数的定义
       getopt()使用optstring所指的字串作为短参数列表,象"1ac:d::"就是一个短参数列表。短参数的定义是一个'-'后面跟一个字母或数字,象-a, -b就是一个短参数。每个数字或字母定义一个参数。 
  其中短参数在getopt定义里分为三种:
  1. 不带值的参数,它的定义即是参数本身。
  2. 必须带值的参数,它的定义是在参数本身后面再加一个冒号。
  3. 可选值的参数,它的定义是在参数本身后面加两个冒号 。
  在这里拿上面的"1ac:d::"作为样例进行说明,其中的1,a就是不带值的参数,c是必须带值的参数,d是可选值的参数。
  在实际调用中,'-1 -a -c cvalue -d', '-1 -a -c cvalue -ddvalue', '-1a -ddvalue -c cvalue'都是合法的。这里需要注意三点:
  1. 不带值的参数可以连写,象1和a是不带值的参数,它们可以-1 -a分开写,也可以-1a或-a1连写。
  2. 参数不分先后顺序,'-1a -c cvalue -ddvalue'和'-d -c cvalue -a1'的解析结果是一样的。
  3. 要注意可选值的参数的值与参数之间不能有空格,必须写成-ddvalue这样的格式,如果写成-d dvalue这样的格式就会解析错误。

返回值
   getopt()每次调用会逐次返回命令行传入的参数。
   当没有参数的最后的一次调用时,getopt()将返回-1。
    当解析到一个不在optstring里面的参数,或者一个必选值参数不带值时,返回'?'。
   当optstring是以':'开头时,缺值参数的情况下会返回':',而不是'?' 。

点击(此处)折叠或打开

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


点击(此处)折叠或打开

  1. $ ./getopt -a
  2.     other option :?
  3.     optopt +a
  4.     $ ./getopt -b
  5.     option b :b
  6.     optopt +
  7.     $ ./getopt -c
  8.     other option :c
  9.     optopt +
  10.     $ ./getopt -d
  11.     other option :d
  12.     optopt +
  13.     $ ./getopt -abcd
  14.     option a:'bcd'
  15.     optopt +
  16.     $ ./getopt -bcd
  17.     option b :b
  18.     other option :c
  19.     other option :d
  20.     optopt +
  21.     $ ./getopt -bcde
  22.     option b :b
  23.     other option :c
  24.     other option :d
  25.     other option :e
  26.     optopt +
  27.     $ ./getopt -bcdef
  28.     option b :b
  29.     other option :c
  30.     other option :d
  31.     other option :e
  32.     other option :?
  33.     optopt +f

上面是getopt()函数的基本含义,大家懂得了这些之后,我们一个例子加深一下理解。
在看下面的例子前注意这几个重要的变量,尤其是optind
extern int optind,  // 初始化值为1,下一次调用getopt时,从optind存储的位置重新开始检查选项,也就是从下一个'-'的选项开始。
extern int opterr,  // 初始化值为1,当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt;  // 当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回’?’。 

 extern char *optarg;  //选项的参数指针


例如我们这样调用getopt(argc, argv, "ab:c:de::");
从上面我们可以知道,选项a,d没有参数,选项b,c有一个参数,选项e有有一个参数且必须紧跟在选项后不能以空格隔开。getopt首先扫描argv[1]到argv[argc-1],并将选项及参数依次放到argv数组的最左边,非选项参数依次放到argv的最后边。

执行程序为:
              5        
$ ./test file1 -a -b -c code -d file2 -e file3
 扫 描过程中,optind是下一个选项的索引, 非选项参数将跳过,同时optind增1。optind初始值为1。当扫描argv[1]时,为非选项参数,跳过,optind=2;扫描到-a选项时, 下一个将要扫描的选项是-b,则optind更改为3;扫描到-b选项时,后面有参数(会认为-c为选项b的参数),optind=5,扫描到code非 选项跳过optind=6;扫描到-d选项,后面没有参数,optind=7;扫描到file2非选项跳过optind=8;扫描到-e后面本来应该有参 数,optind=9但是有空格所以e的参数为空。(optind是每次调到下一个选项,当不是‘-’开头的的时候就自动跳过)
 
扫描结束后,getopt会将argv数组修改成下面的形式
          2                    9
$ ./test -a -b -c -d -e file1 code file2 file3
 
同时,optind会指向非选项的第一个参数,如上面,optind将指向file1
代码如下:


点击(此处)折叠或打开

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. int main(int argc, char * argv[])
  4. {
  5.    int aflag=0, bflag=0, cflag=0;
  6.    int ch;
  7. printf("optind:%d,opterr:%d\n",optind,opterr);
  8. printf("--------------------------\n");
  9.    while ((ch = getopt(argc, argv, "ab:c:de::")) != -1)
  10.    {
  11.        printf("optind: %d,argc:%d,argv[%d]:%s\n", optind,argc,optind,argv[optind]);
  12.        switch (ch) {
  13.        case 'a':
  14.            printf("HAVE option: -a\n\n");
  15.     
  16.            break;
  17.        case 'b':
  18.            printf("HAVE option: -b\n");
  19.          
  20.            printf("The argument of -b is %s\n\n", optarg);
  21.            break;
  22.        case 'c':
  23.            printf("HAVE option: -c\n");
  24.            printf("The argument of -c is %s\n\n", optarg);

  25.            break;
  26.    case 'd':
  27.       printf("HAVE option: -d\n");
  28.       break;
  29.    case 'e':
  30.       printf("HAVE option: -e\n");
  31.       printf("The argument of -e is %s\n\n", optarg);
  32.       break;

  33.        case '?':
  34.            printf("Unknown option: %c\n",(char)optopt);
  35.            break;
  36.        }
  37.    }
  38.    printf("----------------------------\n");
  39.    printf("optind=%d,argv[%d]=%s\n",optind,optind,argv[optind]);
  40. }
shiqi@wjl-desktop:~/code$ vim getopt.c
shiqi@wjl-desktop:~/code$ gcc getopt.c -o g
shiqi@wjl-desktop:~/code$ ./g file1 -a -b -c code -d file2 -e file3
optind:1,opterr:1
--------------------------
optind: 3,argc:10,argv[3]:-b
HAVE option: -a

optind: 5,argc:10,argv[5]:code
HAVE option: -b
The argument of -b is -c

optind: 7,argc:10,argv[7]:file2
HAVE option: -d

optind: 9,argc:10,argv[9]:file3
HAVE option: -e
The argument of -e is (null)   

----------------------------
optind=6,argv[6]=file1        //while循环执行完后,optind=6

主要解释getopt_long()。

    getopt_long()的头两参数,argc和argv分别是传递给main()的参数的个数和参数数组(和main()的argc和argv是一个概念)。

    getopt_long()中,optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面

跟有更多的参数值。(例如:-a host --b name)

    getopt_long()中,参数longopts,其实是一个结构的实例:


点击(此处)折叠或打开

  1. struct option {
  2.   const char *name;
  3.     //name表示的是长参数名
  4.   int has_arg;
  5.     //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值
  6.     // required_argument(或者是1),表示该参数后面一定要跟个参数值
  7.     // optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
  8.   int *flag;
  9.     //用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值
  10.   int val;
  11.     //和flag联合决定返回值
  12. }
给个例子

点击(此处)折叠或打开

  1. struct option long_options[] = {
  2.   {"a123", required_argument, 0, 'a'},
  3.   {"c123", no_argument, 0, 'c'},
  4. }

现在,如果命令行的参数是-a 123,那么调用getopt_long()将返回字符'a',并且将字符串123由optarg返回(注意注意!字符串123由optarg带

回!optarg不需要定义,在getopt.h中已经有定义)
那么,如果命令行参数是-c,那么调用getopt_long()将返回字符'c',而此时,optarg是null。

最后,当getopt_long()将命令行所有参数全部解析完成后,返回-1。

看来,我说的有点混乱,那么,看个例子,我相信,代码最能说明问题:


点击(此处)折叠或打开

  1. #include
  2. #include<p>#include
  3. #include
  4. #include
  5. #include</p><p>int main( int argc, char **argv )
  6. {</p><p> struct option long_options[] = {
  7.    {"a123", required_argument, 0, 'a'},
  8.    {"c123", no_argument, 0, 'c'},
  9.  }
  10.  int opt;
  11.  
  12.  printf("starting... ");
  13.  
  14.  while((opt = getopt_long(argc, argv, "a:c", long_options, NULL)) != -1)
  15.  {
  16.   switch (opt)
  17.   {
  18.   case 'a':
  19.     printf("It's a! ");
  20.     printf("string of a:%s ",optarg);
  21.   break;
  22.     
  23.   case 'c':
  24.     printf("It's c! ");
  25.   break;
  26.     
  27.   default:
  28.     printf("You should look for help! ");
  29.     exit(1);
  30.   break;
  31.   }
  32.  }
  33.  printf("end... ");
  34.  return 0;
  35. }</p>
  36. #include
  37. #include

  38. int main( int argc, char **argv )
  39. {

  40.  struct option long_options[] = {
  41.    {"a123", required_argument, 0, 'a'},
  42.    {"c123", no_argument, 0, 'c'},
  43.  }
  44.  int opt;
  45.  
  46.  printf("starting... ");
  47.  
  48.  while((opt = getopt_long(argc, argv, "a:c", long_options, NULL)) != -1)
  49.  {
  50.   switch (opt)
  51.   {
  52.   case 'a':
  53.     printf("It's a! ");
  54.     printf("string of a:%s ",optarg);
  55.   break;
  56.     
  57.   case 'c':
  58.     printf("It's c! ");
  59.   break;
  60.     
  61.   default:
  62.     printf("You should look for help! ");
  63.     exit(1);
  64.   break;
  65.   }
  66.  }
  67.  printf("end... ");
  68.  return 0;
  69. }
编译后,假设生成a.out,可以试验一下。
./a.out -a hello -c
输出:
starting...
It's a!
string of a:hello
It's c!
end...




阅读(526) | 评论(1) | 转发(0) |
0

上一篇:fgets,fputs,snprintf等

下一篇:经典链接

给主人留下些什么吧!~~

bjutslg2014-02-22 18:13:04

文明上网,理性发言...