getopt----解析命令选项及参数

来源:互联网 发布:msoffice2016 for mac 编辑:程序博客网 时间:2024/06/05 13:32

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

何为 选项 ,参数**

字符串 optstring 可以下列元素

1.但个字符,表示选项
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。 参数紧跟着在选项后面或者以空格隔开。该参数的指针赋给optarg.
3.单个字符后跟两个冒号::,表示该选项后必跟一个参数。参数必须紧跟在选项后,不能以空格隔开。该参数的指针赋给optarg.
4.默认情况下,getopt会重新排列命令参数的顺序,所以到最后所有不包括选项的命令参数都排到最后。

getopt处理以“-”开头的命令行参数,optstring=”ab:c::d::”,命令行为getopt.exe -a -b host -ckeke -d haha

如: getopt.exe -a ima -b host -ckeke -d haha
-a,-b host,-ckeke, ima -d haha

解析:
extern char *optarg ;//选项的参数指针
extern int optind;//下次调用getopt,从optind存储的位置重新开始检查选项
extern int opterr,//pterr=0,getopt不向stderr输出错误信息
extern int optopt;//当命令行选项字符不包括在optstring 中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回“?“

例题
include

int main(int argc,char **argv)

{

int ch;

opterr = 0;

while((ch = getopt(argc,argv,”a:bcde”))!= -1)

{

switch(ch)

{

case ‘a’: printf(“option a:’%s’\n”,optarg); break;

case ‘b’: printf(“option b :b\n”); break;

default: printf(“other option :%c\n”,ch);

}

printf(“optopt +%c\n”,optopt);

}

}

执行 $./getopt –b

option b:b

执行 $./getopt –c

other option:c

执行 $./getopt –a

other option :?

执行 $./getopt –a12345

option a:’12345’