2010年3月29日星期一

UNIX中getopt()使用心得(转)

转:http://www.diybl.com/course/3_program/c++/cppjs/20090205/154853.html
getopt()是UNIX中分析命令行参数的一个函数,很多论坛上有关于它用法的一些讲解,但其描述语言总会令初学者迷茫不堪,
这个函数的代码我也没有看到,只是通过一些输入输出来大概认识它。以下就是我自己的一些心得,希望对大家的使用有所帮助。

表头文件
#include

函数原型
int getopt(int argc, char * const argv[], const char* optstring)

函数说明
参数argc和argv是由main()传递的参数个数和内容,argc计算参数的个数是以空格为分隔符的;
参数optstring则表示欲处理的选项字符串,optstring选项字符串可能有以下三种格式的字符:
1.单个字符,表示选项
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg
3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
举例:optstring="a:b::cd",表示选项a还跟有参数,可能以空格隔开,选项b后还跟有参数,直接接在选项后面,选项c,d均无参数。
补充一点,该函数判断是选项或是参数,依据是字符(串)是否是以-开头,如-ab中,-a为选项,b则为参数

其他说明
此函数影响的全局变量有四个
extern char *optarg; //选项的参数指针
extern int optind, //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回'?’、

返回值
(1)如果选项和optstring中的某一个选项匹配,则返回该选项对应的值
(2)如果不匹配,则返回?
(3)全部分析结束,返回-1

读者可能尚存的疑问:
(1)可带参数的选项后面的参数有两个或两个以上时,optargv的值是什么?
(2)可带参数的选项后面的参数不存在时,optargv的值是多少?
(3)不带参数的选项后有一个或者多个参数时,optargv的值是什么?
以上问题的答案是:
(1)optargv只会取选项后面所跟的第一个字符(串),而忽略其后所有的参数
(2)此时该选项对函数来说不可识别,optargv自然也为NULL
注意,如果此时直接接另一个选项,会把该选项当作是前一个前项的参数处理
(3)对这些参数函数不予处理,optargv的值仍为NULL


下面我们通过一个具体的例子来说明上述结论

源代码:
==============================================================================================================
#include
#include

int main(int argc, char**argv)
{
int ch;
opterr=0; // no printed errors
while((ch=getopt(argc,argv,"a:b:c::d"))!=-1)
switch(ch){
case 'a':
printf("when the option is a, optind=%d, optargv=%s, optopt=%d\n", optind, optargv, optopt);
break;
case 'b':
printf("when the option is b, optind=%d, optargv=%s, optopt=%d\n", optind, optargv, optopt);
break;
case 'c':
printf("when the option is c, optind=%d, optargv=%s, optopt=%d\n", optind, optargv, optopt);
break;
case 'd';
printf("when the option is d, optind=%d, optargv=%s, optopt=%d\n", optind, optargv, optopt);
break;
default:
printf("other options, optind=%d, optargv=%s, optopt=%c\n", optind, optargv, optopt);
}
}
==============================================================================================================

输出:
=====================================================================
input: $./func -aaaa -b bbb -cccc -c ccc -d ddd -e eee

output: when the option is a, optind=2, optargv=aaa, optopt=?
when the option is b, optind=4, optargv=bbb, optopt=?
when the option is c, optind=5, optargv=ccc, optopt=?
when the option is d, optind=6, optargv=(null), optopt=?
other options, optind=8, optargv=(null), optopt=?
other options, optind=10, optargv=(null), optopt=e
===================================================================

没有评论: