获取连接参数
Getopt joining parameters
是否有办法使用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()
能处理好吗?或者我必须编写复杂的解析器才能做到这一点?
除了缺少大括号,您的代码对我来说工作得很好:
#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("Ln");
break;
case 'U':
// U catch
printf("Un");
break;
default:
break;
}
}
return 0;
}
$ ./a.out -LU L U $ ./a.out -L L $
它的行为完全符合您的要求:
#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()
是一个POSIX标准函数,遵循POSIX"实用程序语法指南",其中包括以下内容:
指南5:当将没有选项参数的选项分组在一个'-'分隔符后面时,应该接受这些选项。
getopt
似乎有能力处理它,而且
下面是一些示例,展示了该程序使用不同的参数组合输出的内容:
% testopt
aflag = 0, bflag = 0, cvalue = (null)
% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)
% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)
相关文章:
- Qt5:连接:如果插槽的参数少于信号,如何使用"连接"
- Wt 连接函数,将参数传递给作为连接函数参数的函数
- 文档在哪里说明如果参数不是从末端删除参数,则无法从QT信号插槽连接中删除参数?
- 使用libpq组织PostgreSQL数据库连接参数
- 如何使用分隔符连接命令行参数
- 当条件为真时,有没有办法连接宏参数
- Qt - 使用λ函数修改先前连接信号的插槽参数
- 使用"const char*"和"char*"参数连接两个第三方模块
- 在参数包中获取函数指针的返回类型,并将其保存为与其他参数连接的元组
- 无法为 QT 连接函数提供参数
- 在可变参数模板函数中连接字符串(和数字)
- Qt用参数将QAction连接到函数
- C++连接函数错误-参数无效
- C++ 将两个字符 * 连接到命令行参数的 LPTSTR
- 为连接的OMNeT++门分配随机选择但匹配的参数
- 正在将QAxObject事件与IDispatch*类型的参数连接
- 将返回对象的信号连接到没有参数的插槽
- c++:将其所有参数连接为字符串的函数
- Qt:上下文菜单/与参数连接
- 宏参数连接不像我预期的那样工作