linux C语言getopt()函数的使用

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

 

执行效果:

 

01.$ ./getopt -a  
02.other option :?  
03.optopt +a  
04.$ ./getopt -b  
05.option b :b  
06.optopt +  
07.$ ./getopt -c  
08.other option :c  
09.optopt +  
10.$ ./getopt -d  
11.other option :d  
12.optopt +  
13.$ ./getopt -abcd  
14.option a:'bcd' 
15.optopt +  
16.$ ./getopt -bcd 
17.option b :b 
18.other option :c  
19.other option :d  
20.optopt +  
21.$ ./getopt -bcde  
22.option b :b  
23.other option :c 
24.other option :d  
25.other option :e  
26.optopt +  
27.$ ./getopt -bcdef  
28.option b :b  
29.other option :c  
30.other option :d  
31.other option :e  
32.other option :?  
33.optopt +f  

 

 

 

posted on 2013-08-28 22:01  鹰之翔  阅读(1961)  评论(0编辑  收藏  举报

导航