getopt 用法

getopt函数用于解析命令行参数,如经常用到带选项的输入,如netstat –n / find –name filename 等等。下面谈谈其相关内容:

包含头文件:unistd.h

全局参数:

int opterr; //这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。

char *optarg; //跟在带参数的选项后面的参数,如上面的filename

int optind; //argv的当前索引值,随着解析的过程增加

int optopt; //当发现无效选项字符之时,getopt()函数或返回'?'字符,无效字符会被记录到optopt中

code:

#include <unistd.h>
#include <stdio.h>
int main(int argc, char **argv)
{
       intc;
       while((c= getopt(argc, argv, "ag:")) != -1)
       {
              switch(c)
              {
                     case'g':
                            printf("%s,optind = %d
", optarg, optind);
                            break;
                     case'a':
                            printf("%s,optind= %d
","catch -a", optind);
                            break;
                     case'?':
                            printf("erroroccur,optind = %d, c = %c, opterr = %d 
", optind, (char)optopt);
                            break;
                     case':':
                            printf("-%cshould follow a value
", (char)optopt);
                     default:
                            printf("unknown,c = %c
", (char)optopt);
              }
       }
} 

编译运行得到如下结果


原文地址:https://www.cnblogs.com/OpenLinux/p/5020705.html