Chinaunix首页 | 论坛 | 博客
  • 博客访问: 10475857
  • 博文数量: 2905
  • 博客积分: 20098
  • 博客等级: 上将
  • 技术积分: 36298
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-23 05:00
文章存档

2012年(1)

2011年(3)

2009年(2901)

分类: LINUX

2009-03-23 11:23:22

系统调用getopt

声明:
#include
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包含了所发现的无效选项字符。

例子:
/* getopttest.c ── 练习系统调用getopt()的用法,为实现shell内置命令getopts和各个命令的命令行参数解析做准备 */
#include
#include
// 程序接受两个参数:-a -b ,其中-b选项必需带一个参数(整数)
int main(int argc, char *argv[])
{
int oc;
char * b_opt_arg;

while((oc = getopt(argc, argv, "ab:")) != -1)
{
switch(oc)
{
case 'a':
printf("have option -a\n");
break;
case 'b':
b_opt_arg = optarg;
int count = atoi(b_opt_arg);
// 输出count个have option b, arg is `count`
int i = 0;
for (i = 0; i < count; i++)
printf("have option -b, arg is %s\n", b_opt_arg);;
break;
case ':':
// 缺少选项参数
fprintf(stderr, "%s: option '-%c' is invalid: ignored\n", argv[0], optopt);
break;
case '?':
default:
// 无效选项
fprintf(stderr, "%s: option '-%c' is invalid: ignored\n", argv[0], optopt);
break;
}
}
}
编译、运行 :

阅读(814) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~