1

我的代码使用 getopt 从命令行获取参数。我希望能够采用三个必需的参数和一个可选的第四个参数。我们分别称这些输入 A 和 B./main string1 string2 filename./main -n 3 string1 string2 filename

有人告诉我,可选参数不需要放在开头,因此以下内容也应该有效。让我们将此输入 C : ./main string1 string2 -n 3 filename。请注意,其他 3 个参数必须按此顺序排列。这是我遇到麻烦的部分。

目前,我的代码如下所示:

int c;
int n;
while ((c = getopt(argc,argv,"n:"))!=-1) {
    printf("Loop\n");
    switch (c) {
            case 'n':
                cvalue = optarg;
                n = atoi(optarg);
                break;
            case '?':
                break;
            default:
                break;
    }
}

如果我输入 B,则代码有效,即进入循环并且输入正确分配给 n。但是,如果我输入 C,它甚至不会进入循环,即它似乎甚至没有在参数中注册 -n 3。这是预期的行为,还是我的代码中缺少某些内容?我该如何解决这个问题?

4

1 回答 1

0

getopt() 实现了“标准”命令行结构,即所有选项都在所有参数(ref)之前。并非所有的 Unix 命令都遵循这个“标准”;如果您的命令需要偏离,您可以手动解析 argv[],而无需使用 getopt() 函数。来自 man 3 getopt:

If there are no more option  characters,  getopt()  returns  -1.   Then
optind  is  the  index in argv of the first argv-element that is not an
option.
于 2013-09-22T18:15:45.440 回答