getopt()函数用法

来源:互联网 发布:淘宝第三层级 编辑:程序博客网 时间:2024/04/28 08:13

getopt用法

有关系统调用getopt:
声明:
         #include <unistd.h>
         int getopt(int argc, char *const argv[], const char *optstring);

         extern char *optarg;
         extern int optind, opterr, optopt;

使用方法:在while循环中反复调用,直到它返回-1。每当找到一个有效的选项字母,它就返回这个字母。如果选项有参数,就设置optarg指向这个参数。
当程序运行时,getopt()函数会设置控制错误处理的几个变量:
char *optarg ──如果选项接受参数的话,那么optarg就是选项参数。
int optind──argv的当前索引,当while循环结束的时候,剩下的操作数在argv[optind]到argv[argc-1]中能找到。
int opterr──当这个变量非零(默认非零)的时候,getopt()函数为"无效选项”和“缺少选项参数”这两种错误情况输出它自己的错误消息。可以在调用getopt()之前设置opterr为0,强制getopt()在发现错误时不输出任何消息。
int optopt──当发现无效选项,getopt()函数或者返回'?'字符,或者返回字符':'字符,并且optopt包含了所发现的无效选项字符。

头文件:#include     <unistd.h>   
    
    函数声明:int     getopt(int     argc,     char     *     const     argv[],     const     char     *optstring);   
    函数说明:getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数optstring     则代表欲处理的选项字符串。此函数会返回在argv     中下一个的选项字母,此字母会对应参数optstring     中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg     即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。   
    
    返回值:如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring     的选项字母则返回“?”字符,分析结束则返回-1。   
    #include     <unistd.h>   
    #include     <stdio.h>   
    int     main(int     argc,     char     **argv)   
    {   
            int     ch;   
            opterr     =     0;   
            while(     (     ch     =     getopt(     argc,     argv,     "s:b:c:p:"     )     )     !=     EOF     )   
            {   
                    switch(ch)   
                    {   
                            case     's':   
                                    printf("s     opt:     %s/n",     optarg);   
                                    break;   
                            case     'b':   
                                    printf("b     opt:     %s/n",     optarg);   
                                    break;   
                            case     'c':   
                                    printf("c     opt:     %s/n",     optarg);   
                                    break;   
                            case     'p':   
                                    printf("p     opt:     %s/n",     optarg);   
                                    break;   
                            case     '?':   
                                    printf(     "illegal     option:     %c/n",     ch     );   
                                    break;   
                    }             

 

——————————————————————————————————————————————————

getopt()函数的原型为getopt(int argc,char *const argv[],const char *optstring)。
其中argc和argv一般就将main函数的那两个参数原样传入。
optstring是一段自己规定的选项串,例如"a:b::cde",表示可以有 -a,-b,-c,-d,-e这几个参数。
“:”表示必须该选项带有额外的参数,全域变量optarg会指向此额外参数,“::”标识该额外的参数可选(有些Uinx可能不支持“::”)。
全域变量optind指示下一个要读取的参数在argv中的位置。
如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符。
如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。