获取连接参数

Getopt joining parameters

本文关键字:参数 连接 获取      更新时间:2023-10-16

是否有办法使用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)