getopt的用法

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

点击(此处)折叠或打开

  1. #include <unistd.h>
  2. extern char *optarg; //选项的参数指针
  3. extern int optind, //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
  4. extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。
  5. extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回'?’、
  6. 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和-h就是选项元素,去掉'-',a,b,c就是选项。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。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. int main(int argc, char **argv)
  5. {
  6. int result;
  7. opterr = 0; //使getopt不行stderr输出错误信息
  8. while( (result = getopt(argc, argv, "ab:c::")) != -1 )
  9. {
  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. }

unistd里有个 optind 变量,每次getopt后,这个索引指向argv里当前分析的字符串的下一个索引,因此
argv[optind]就能得到下个字符串,通过判断是否以 '-'开头就可。下面是个测试程序

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. int main(int argc, char* argv[])
  4. {
  5. int tmp = 4;
  6. while( (tmp = getopt(argc, argv, "abck")) != -1 )
  7. {
  8. printf("-%c\t", tmp);
  9. int opt = optind ;
  10. while( opt < argc )
  11. {
  12. if ( argv[opt][0] != '-' )
  13. {
  14. printf("%s\t", argv[opt]);
  15. opt ++;
  16. }
  17. else
  18. break;
  19. }
  20. printf("\n");
  21. }
  22. getchar();
  23. }

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

返回值  如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1。
范例

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<unistd.h>
  3. int main(int argc,char **argv)
  4. {
  5. int ch;
  6. opterr = 0;
  7. while((ch = getopt(argc,argv,”a:bcde”))!= -1)
  8. switch(ch)
  9. {
  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. }

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<unistd.h>
  3. int main(int argc,char **argv)
  4. {
  5. int ch;
  6. opterr = 0;
  7. while((ch = getopt(argc,argv,”a:bcde”))!= -1)
  8. switch(ch)
  9. {
  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. }

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

getopt 函数

函数定义:

点击(此处)折叠或打开

  1. #include
  2. int getopt(int argc, char * const argv[],
  3. const char *optstring);
  4. extern char *optarg;
  5. extern int optind, opterr, optopt;
  6. #define _GNU_SOURCE
  7. #include
  8. int getopt_long(int argc, char * const argv[],
  9. const char *optstring,
  10. const struct option *longopts,
  11. int *longindex);
  12. int getopt_long_only(int argc, char * const argv[],
  13. const char *optstring,
  14. const struct option *longopts,
  15. int *longindex);

getopt()函数是用来解析命令行参数的。这里,主要解释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,其实是一个结构的实例:
struct option {
  const char *name;
    //name表示的是长参数名
  int has_arg;
    //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值
    //   required_argument(或者是1),表示该参数后面一定要跟个参数值
    //   optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
  int *flag;
    //用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值
  int val;
    //和flag联合决定返回值
}

给个例子:

struct option long_options[] = {
  {"a123",       required_argument,      0, 'a'},
  {"c123",       no_argument,            0, 'c'},
}

现在,如果命令行的参数是-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
  3. #include
  4. #include
  5. int main( int argc, char **argv )
  6. {
  7. struct option long_options[] = {
  8. {"a123", required_argument, 0, 'a'},
  9. {"c123", no_argument, 0, 'c'},
  10. }
  11. int opt;
  12. printf("starting... ");
  13. while((opt = getopt_long(argc, argv, "a:c", long_options, NULL)) != -1)
  14. {
  15. switch (opt)
  16. {
  17. case 'a':
  18. printf("It's a! ");
  19. printf("string of a:%s ",optarg);
  20. break;
  21. case 'c':
  22. printf("It's c! ");
  23. break;
  24. default:
  25. printf("You should look for help! ");
  26. exit(1);
  27. break;
  28. }
  29. }
  30. printf("end... ");
  31. return 0;
  32. }

编译后,假设生成a.out,可以试验一下。
./a.out -a hello -c
输出:
starting...
It's a!
string of a:hello
It's c!
end...

C++中的getopt的用法的更多相关文章

  1. linux中getopt的用法-(转自pengyingh)

    getopt被用来解析命令行选项参数.就不用自己写东东处理argv了. #include <unistd.h>       extern char *optarg;   //选项的参数指针 ...

  2. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  3. ecshop中foreach的详细用法归纳

    ec模版中foreach的常见用法. foreach 语法: 假如后台:$smarty->assign('test',$test); {foreach from=$test item=list ...

  4. matlab中patch函数的用法

    http://blog.sina.com.cn/s/blog_707b64550100z1nz.html matlab中patch函数的用法——emily (2011-11-18 17:20:33) ...

  5. C#中timer类的用法

    C#中timer类的用法 关于C#中timer类  在C#里关于定时器类就有3个   1.定义在System.Windows.Forms里   2.定义在System.Threading.Timer类 ...

  6. C#中dynamic的正确用法

    C#中dynamic的正确用法  http://www.cnblogs.com/qiuweiguo/archive/2011/08/03/2125982.html dynamic是FrameWork4 ...

  7. C++中typename关键字的用法

    我在我的 薛途的博客 上发表了新的文章,欢迎各位批评指正. C++中typename关键字的用法

  8. Guava中Predicate的常见用法

    Guava中Predicate的常见用法 1.  Predicate基本用法 guava提供了许多利用Functions和Predicates来操作Collections的工具,一般在 Iterabl ...

  9. C++中const 的各种用法

    C++中const 关键字的用法 const修饰变量 const 主要用于把一个对象转换成一个常量,例如: ; size = ; // error: assignment of read-only v ...

随机推荐

  1. 解决wordpress部分博客文章页面无法显示的问题

    搭建完wordpress,试着写了一篇博客.文章发布后,首页已经能显示出文章的标题,但是点进去后却提示该页无法显示. 百度一番,先后尝试网上的修改apache配置等方法后依然无效.折腾到最后无意间发现 ...

  2. “玲珑杯”ACM比赛 Round #19

    A -- A simple math problem Time Limit:2s Memory Limit:128MByte Submissions:1599Solved:270 DESCRIPTIO ...

  3. .NET重构(六):删除用户和结账的理解

    导读:这是第二回机房了,第一回不明不白,不清不楚的就过去了(相对),这一回,有了新的发现.就是在用户删除的时候,涉及到的一些逻辑问题,以及结账时的数据来源问题. 一.用户删除 问题:第一次机房,包括重 ...

  4. vscode & code snippets

    code snippets vscode & code snippets https://github.com/xgqfrms/FEIQA/tree/master/000-xyz/templa ...

  5. Educational Codeforces Round 13——D. Iterated Linear Function(矩阵快速幂或普通快速幂水题)

      D. Iterated Linear Function time limit per test 1 second memory limit per test 256 megabytes input ...

  6. BZOJ 3028 食物 ——生成函数

    把所有东西的生成函数搞出来. 发现结果是x*(1-x)^(-4) 然后把(1-x)^(-4)求逆,得到(1+x+x^2+...)^4 然后考虑次数为n的项前的系数,就相当于选任意四个非负整数构成n的方 ...

  7. Cstring中GetBuffer()方法的主要作用

    摘自:http://bbs.csdn.net/topics/310247836 GetBuffer()主要作用是将字符串的缓冲区长度锁定   CString::GetBuffer有两个重载版本: (1 ...

  8. iOS 收款计算器算法

    一个收款计算器算法,从之前高仿有赞Demo里面抽离的一个界面 demo 在这里 https://github.com/L-vinCent/calculView_function 显示计算记录 不能连续 ...

  9. Hubtown

    Hubtown 时间限制: 10 Sec  内存限制: 256 MB 题目描述 Hubtown is a large Nordic city which is home to n citizens. ...

  10. android源码mk文件里的TARGET_OUT指向哪里?

    android源码核心变量大都在build/core/envsetup.mk中建立 在该文件中,可以找到 TARGET_OUT := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_ ...