Chinaunix首页 | 论坛 | 博客
  • 博客访问: 465282
  • 博文数量: 93
  • 博客积分: 5006
  • 博客等级: 上校
  • 技术积分: 1002
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-30 13:58
文章分类

全部博文(93)

文章存档

2012年(2)

2011年(68)

2010年(23)

分类: LINUX

2011-07-25 20:09:35

getopt函数是分析命令行参数,简单说就是判断你是否有使用某个参数,有则返回参数,没有返回-1。
 
表头文件是#include
 
函数原型为:int getopt(int argc,char * const argv[ ],const char * optstring);
 
函数说明如下
   getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,例如下面例子中的
”a:bcde”,a不是一个单独的命令参数,由于它后边存在:,则加上后边的参数才算一个整体,(这只是我的理解)。

全局变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可(如下例子中就把opterr设为0了)。
 
返回值:如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1。
 

例子:

#include
#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);
}

编译后运行结果

panda@panda-pc:~/Code/linux/Mqueue$ ls
b  mqcreatel  mqcreatel.c  test_getopt  test_getopt.c
panda@panda-pc:~/Code/linux/Mqueue$ ./test_getopt -b
option b :b
optopt +
panda@panda-pc:~/Code/linux/Mqueue$ ./test_getopt -a
other option :?
optopt +a
panda@panda-pc:~/Code/linux/Mqueue$ ./test_getopt -a -b -e
option a:'-b'
other option :e
optopt +
panda@panda-pc:~/Code/linux/Mqueue$ ./test_getopt -a -b -e -c -d
option a:'-b'
other option :e
other option :c
other option :d
optopt +

panda@panda-pc:~/Code/linux/Mqueue$ ./test_getopt -a:1234
option a:':1234'
optopt +


有二个问题
一、如果getopt()找不到符合的参数则会返回‘?’,全域变量optopt存储的是无效字符,那./test_getopt -a后为什么potpot的值输出的是a

是因为a在这个运行里面是无效的


二、
我不理解 这个 panda@panda-pc:~/Code/linux/Mqueue$ ./test_getopt -a:1234
option a:':1234'
optopt +
1234为什么可以找到?

因为a后边存在':',所以国得的参数理应是a后边的一切字符





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