【问题标题】:Getopt joining parametersGetopt 加入参数
【发布时间】:2013-02-26 02:37:56
【问题描述】:
有没有办法使用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() 可以处理这个吗?还是我必须编写复杂的解析器才能做到这一点?
【问题讨论】:
标签:
c++
c
parameters
parameter-passing
getopt
【解决方案1】:
getoptdoes 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)
【解决方案2】:
它的行为完全符合您的意愿:
#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' option
getopt() is a POSIX standard function 跟在POSIX "Utiltiy Syntax Guidelines" 之后,包括以下内容:
准则 5:
当分组在一个“-”分隔符后面时,应该接受没有选项参数的选项。
【解决方案3】:
保存缺少的大括号,您的代码对我来说很好:
#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;
}
$ ./a.out -LU
L
U
$ ./a.out -L
L
$