getopt被用来解析命令行选项参数。

#include <unistd.h>

函数及参数介绍

extern char *optarg; //选项的参数指针,如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。

extern int optind,  //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。

extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。

extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt 中,getopt返回'?’

int getopt(int argc, char * const argv[], const char *optstring); 调用一次,返回一个选项。在命令行选项参数再也检查不到optstring中包含的选项时,返回-1,同时optind储存第一个不包含选项的命令行参数。

什么是选项,什么是参数

1.单个字符,表示选项,

2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。

3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。

测试代码:

 

 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  }  
View Code

相关文章:

  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
猜你喜欢
  • 2021-11-07
  • 2021-08-06
  • 2021-09-17
  • 2022-02-13
  • 2021-11-26
  • 2022-12-23
相关资源
相似解决方案