getopt函数的使用

来源:互联网 发布:流程优化的方法 编辑:程序博客网 时间:2024/06/05 03:45
 #include <unistd.h>

int getopt(int argc, char * const argv[], const char *optstring);

这是getopt函数的原型

函数用来分析命令行参数,有三个参数,argc表示参数个数,argv表示参数内容,optstring表示可选选项,重点就在于optstring的内容

argc和argv直接由主函数传递,optstring需要从命令行输入

我们从代码来简单解释



 #include<unistd.h>
  2 #include<stdio.h>
  3
  4
  5 int main(int argc,char **argv[])
  6 {
  7     char ch;
  8     while((ch = getopt(argc,argv,"abf:d::")) != -1)
  9     {
 10         switch(ch)
 11         {
 12             case 'a':
 13                 printf("option is a\n");
 14                 break;
 15             case 'b':
 16                 printf("option is b\n");
 17                 break;
 18             case 'f':
 19                 printf("my bf is:%s\n",optarg);
 20                 break;
 21             case 'd':
 22                 printf("my gf is:%s\n",optarg);
 23                 break;
 24             case '?':
 25                 printf(" erron\n");
 26                 break;
 27
 28         }
 29     }
 30     return 0;
 31 }
 32


1。如果ch后没有: 无论一个或是几个,就按照正常情况编译 比如如果是case a或者case b就是./test -a

2。如果ch后有:一个,后要加字符,也就是给了第三个参数一个值 ,有空格或者没有空格都是不影响的,./test -f  string

3。但如果ch后有两个::,运行是不能加空格,./test -dfghj

需要注意的是,它加了空格不是说是错误的,而是不识别,系统还是认为你给的字符串为空

hmt@hmt:~/文档/Code/test$ ./test -d fgj
my gf is:(null)
hmt@hmt:~/文档/Code/test$ ./test -dfghj
my gf is:fghj
hmt@hmt:~/文档/Code/test$

4。最后一点,如果你给的选项是无效字符,也就是不在你给的选项内,它会走?分支

hmt@hmt:~/文档/Code/test$ ./test -x
./test: invalid option -- 'x'
 erron
hmt@hmt:~/文档/Code/test$





除此之外,还有一些其他相关的全局变量

  • char *optarg——当前选项参数字串(如果有)。
  • int optind——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。
  • int opterr——这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。
  • int optopt——当发现无效选项字符之时,getopt()函数或返回'?'字符,或返回':'字符,并且optopt包含了所发现的无效选项字符。

原创粉丝点击