免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2849 | 回复: 2
打印 上一主题 下一主题

getopt 对缺少参数的判断返回,为什么就不对呢?是getopt的bug吗? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-10-21 18:52 |只看该作者 |倒序浏览
如果我把缺少参数那个opt写在最后面 那么getopt 是返回“:”
/get_opt.out -u 1000 -o 1 -p
find u, optarg = 1000, optint = 3
find o, optarg = 1, optint = 5
find :, optarg = (null), optint = 7
minssing argusage: ./get_opt.out -p picpath -u uid -o user_act

但是我把缺少参数的那个opt放在中间,结果就完全不对了,没有像网上写的(man也是)返回“:”
./get_opt.out -u 1000 -p -o 1
find u, optarg = 1000, optint = 3
find p, optarg = -o, optint = 5
ooooooooo: uid = 1000, op = -1 , pic = -o

它把 -o 当成了 -p 的参数
这是getopt的bug吗?

我在linux和mac下都是得到上面的答案,难道还得手动去判断第一个字符是否为“-” ???
  1. #include<stdlib.h>
  2. #include<unistd.h>
  3. #include<string.h>
  4. #include<stdio.h>

  5. char * program;

  6. void usage()
  7. {
  8.     printf("usage: %s -p picpath -u uid -o user_act\n", program);
  9.     exit(-1);
  10. }

  11. int main(int argc, char * argv[])
  12. {
  13.     int c;
  14.     int uid = 0 ,op = -1;
  15.     char pic[64] = { 0 };
  16.     program = argv[0];
  17.     opterr = 0;

  18.     while( -1 != (c = getopt(argc, argv, ":u:p:o:")))
  19.     {   

  20.         printf("find %c, optarg = %s, optint = %d\n", c, optarg, optind);
  21.         switch(c) {

  22.         case 'u':
  23.             if(optarg)
  24.                 uid = atoi(optarg);
  25.             break;
  26.         case 'p':
  27.             if(optarg)
  28.                 strcpy(pic, optarg);
  29.             break;
  30.         case 'o':
  31.             if(optarg)
  32.                 op = atoi(optarg);
  33.                 break;
  34.         case ':':
  35.             printf("minssing arg");
  36.         case '?':
  37.         default:
  38.             usage();
  39.         }
  40.     }

  41.     printf("ooooooooo: uid = %d, op = %d , pic = %s\n", uid , op, pic);
  42.     return 0;
  43. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2010-10-21 20:30 |只看该作者
LZ直接看getopt源码嘛 不就知道了么

论坛徽章:
0
3 [报告]
发表于 2010-10-21 23:45 |只看该作者
我也是想问问大家有没有遇到过,也算是个交流
周末有时间去看看源码去,呵呵
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP