首页 > 技术文章 > 解析main函数的命令行参数

zhaojk2010 2016-03-16 20:50 原文

原创文章,转载请正确注明本文原始URL及作者。

介绍

写C/C++程序,我们常常需要把main函数的参数作为选项来传递。在linux中,解析选项有专门的函数可以用。

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

getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。
参数optstring 则代表你想要处理的选项字符串。
此函数处理的是短格式的选项,像"-a"这样只有一个字母的就是选项。
此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的一个字母。
如果选项字符串里的字母后接着冒号":",则表示此选项还有相关的参数,全域变量optarg 即会指向此额外参数。
如果getopt()发现有optstring以外的选项,则返回字符'?'并用全域变量optopt接收该未知选项,并且打印出错信息。如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
这里涉及到三个全局变量: optarg optopt opterr

演示一下

 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,"c:dls"))!=-1)   
 8     {   
 9         switch(ch)   
10         {   
11             case 'c':   
12                 printf("config:%s\n",optarg);   
13                 break;   
14             case 'd':   
15                 printf("debug mode\n");   
16                 break;   
17             case 'l':   
18                 printf("print log\n");   
19                 break;   
20             case 's':   
21                 printf("print status\n");   
22                 break;      
23             default:   
24                 printf("ch=%c,unknown option :%c\n",ch,optopt);   
25         }   
26     }    
27     printf("opterr=%d\n",opterr);   
28 }   

传参测试一下,运行结果如下:

test@localhost:~$ ./a.out -lsd -c hello.ini -AB
print log
print status
debug mode
config:hello.ini
ch=?,unknown option :A
ch=?,unknown option :B 

 

我参考了这个资料,但其中有点错误,他把optopt说反了。

 原创文章,转载请正确注明本文原始URL及作者。

推荐阅读