- 论坛徽章:
- 0
|
如果我把缺少参数那个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下都是得到上面的答案,难道还得手动去判断第一个字符是否为“-” ???- #include<stdlib.h>
- #include<unistd.h>
- #include<string.h>
- #include<stdio.h>
- char * program;
- void usage()
- {
- printf("usage: %s -p picpath -u uid -o user_act\n", program);
- exit(-1);
- }
- int main(int argc, char * argv[])
- {
- int c;
- int uid = 0 ,op = -1;
- char pic[64] = { 0 };
- program = argv[0];
- opterr = 0;
- while( -1 != (c = getopt(argc, argv, ":u:p:o:")))
- {
- printf("find %c, optarg = %s, optint = %d\n", c, optarg, optind);
- switch(c) {
- case 'u':
- if(optarg)
- uid = atoi(optarg);
- break;
- case 'p':
- if(optarg)
- strcpy(pic, optarg);
- break;
- case 'o':
- if(optarg)
- op = atoi(optarg);
- break;
- case ':':
- printf("minssing arg");
- case '?':
- default:
- usage();
- }
- }
- printf("ooooooooo: uid = %d, op = %d , pic = %s\n", uid , op, pic);
- return 0;
- }
复制代码 |
|