当前位置:   article > 正文

getopt--参数选项处理_argv[optind]

argv[optind]

在写一些可执行程序时,常常会传递一些参数。getopt函数就是专门用来处理选项参数的。

  1. #include <unistd.h>
  2. extern char *optarg;
  3. extern int optind, opterr, optopt;
  4. int getopt(int argc, char * const argv[], const char *optstring);

argc和argv就是命令行传入的参数。

optstring是支持的选项列表。具体规则如下:

  • 单一字符(如:"abc")。表示支持的选项,后面无参数。
  • 字符后面跟上冒号(如:"a:b:c:")。表示后面必须跟一个参数,可以紧跟在后面,也可以以空格隔开。例如传参"-a 10 -b20"。此时变量optarg就指向参数位置。
  • 字符后面跟两个冒号(如:"a::")。表示后面必须跟一个参数,且不能以空格隔开。如:"-a20"。此时变量optarg就指向参数位置。

optarg、optind、opterr、optopt:

  • optarg:当选项后面跟参数时,此指针指向参数。
  • optind:这个变量表示当前要处理的参数在argv参数列表中的需要,初始值是1。总之argv[optind]始终是指向下一次要解析的参数序号。
  • opterr:表示错误值。
  • optopt:指向当前选项。比如-a,则optopt就是97.

当getopt解析到一个并不在optstring中的选项时,或者一个必须跟参数的选项后面没有参数时,其返回值就是'?'(0x3f)。optopt指向当前的选项。

了解了上面的接口和相关参数,就可以通过循环调用getopt来解析一长串的参数。

 

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. extern int optind, opterr, optopt;
  5. extern char* optarg;
  6. void show_help(char* exe)
  7. {
  8. printf("Usage: %s -<w/r> [info]\r\n");
  9. }
  10. void main(int argc, char* argv[])
  11. {
  12. int ch;
  13. printf("optind = %d.\r\n", optind);
  14. while ((ch = getopt(argc, argv, "w:rh::")) != -1) {
  15. printf("optind = %d.\r\n", optind);
  16. switch (ch) {
  17. case 'w':
  18. printf("get w. optarg = %s. optind = %d\r\n", optarg, optind);
  19. break;
  20. case 'r':
  21. printf("get r. optarg = %s\r\n", optarg);
  22. break;
  23. case 'h':
  24. printf("get h.\r\n");
  25. break;
  26. default:
  27. printf("default ch = %d. optopt = %d\r\n", ch, optopt);
  28. break;
  29. }
  30. }
  31. printf("end.\r\n");
  32. }

运用好optind、optarg变量,再加上一些具体应用所需的策略,即可完成对命令行参数的解析。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/811986
推荐阅读
相关标签
  

闽ICP备14008679号