getopt()函数 命令解析 Linux下getopt()函数的简单使用

  今天做计算机系统结构实验时学习到一个非常方便的命令解析函数getopt(),简单做个笔记,方便日后复习。
  • 头文件:#include<unistd.h>
  • 函数原型:int getopt(int argc,char * const argv[ ],const char * optstring);
  • 返回值:最后返回-1表示解析结束。
  • 参数解释:
      其中 optstring为选项字符串,比如,"a:b:cd::e",这就是一个选项字符串。对应到命令行就是-a ,-b ,-c ,-d, -e 。
      冒号表示参数:
      没有冒号表示这个选项不带参数;
      一个冒号就表示这个选项后面必须带有参数(没有带参数会报错),但是这个参数可以和选项连在一起写,也可以用空格隔开,比如-a123 和-a   123(中间有空格) 都表示123是-a的参数;
      两个冒号的就表示这个选项的参数是可选的,即可以有参数,也可以没有参数,但要注意有参数时,参数与选项之间不能有空格(有空格会报错的哦),这一点和一个冒号时是有区别的。
  • 涉及的其他变量:

  getopt() 所设置的全局变量包括:

    extern char *optarg;

    extern int     optind;

    extern int     opterr;

    extern int     optopt;

    optarg——指向当前选项参数(如果有)的指针;

    optind——再次调用 getopt() 时的下一个 argv 指针的索引;

    opterr——表示的是是否将错误信息输出到stderr,为0时表示不输出;

    optopt——表示不在选项字符串optstring中的选项。

示例代码:
 
 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   {
 9     switch(ch)
10     {
11     case 'a': printf("option a:’%s’\n",optarg); break;
12     case 'b': printf("option b :b\n"); break;
13     default: printf("other option :%c\n",ch);
14     }
15     printf("optopt +%c\n",optopt);
16   }
17   return 0;
18   }

参考资料:

百度百科    https://baike.baidu.com/item/getopt/4705064?fr=aladdin 

Linux下getopt()函数的简单使用    https://www.cnblogs.com/qingergege/p/5914218.html

猜你喜欢

转载自www.cnblogs.com/x10000zhang/p/10739333.html