有没有办法使用getopt函数来解析:
./prog -L -U等同于:
./prog -LU 这是我的尝试(不起作用):
while ((c = getopt(argc, argv, "LU")) != -1) {
switch (c) {
case 'L':
// L catch
break;
case 'U':
// U catch
break;
default:
return;
}
}在这个简单的例子中只有2个参数,但在我的项目中需要6个参数的所有组合。例如:-L或-LURGHX或-LU -RG -H等,getopt()能处理吗?或者我必须编写复杂的解析器才能这样做?
发布于 2013-03-11 09:26:13
除了缺少一个大括号外,你的代码对我来说工作得很好:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
int c;
while ((c = getopt(argc, argv, "LU")) != -1) {
switch (c) {
case 'L':
// L catch
printf("L\n");
break;
case 'U':
// U catch
printf("U\n");
break;
default:
break;
}
}
return 0;
}发布于 2013-03-11 09:16:45
getopt does seem capable of handling it,and it does
下面是一些示例,展示了此程序使用不同的参数组合打印的内容:
% testopt
aflag = 0, bflag = 0, cvalue = (null)
% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)
% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)发布于 2013-03-11 09:24:16
它的行为完全如您所愿:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char** argv)
{
int c;
while ((c = getopt(argc, argv, "LU")) != -1) {
switch (c) {
case 'L':
puts("'L' option");
break;
case 'U':
// U catch
puts("'U' option");
break;
default:
puts("shouldn't get here");
break;
}
}
return 0;
}并对其进行测试:
precor@burrbar:~$ gcc -o test test.c
precor@burrbar:~$ ./test -LU
'L' option
'U' option
precor@burrbar:~$ ./test -L -U
'L' option
'U' optionPOSIX "Utiltiy Syntax Guidelines"后面的getopt() is a POSIX standard function,包括以下内容:
准则5:不带选项参数的选项在分组到一个'-‘分隔符之后时应该被接受。
https://stackoverflow.com/questions/15329778
复制相似问题