getopt 只接受一个参数

getopt to take only one argument

我有一个关于 C 中的 getopt 的问题。我有多个选项标志,我试图让它对所有内容都采用一个参数。命令行看起来像 command -a fileNamecommand -b fileNamecommand -ab fileName。基本上每个命令都接受一个文件名,如果他们想组合命令,他们只需要输入一个文件名。在 getopt 中,字符串看起来像 a:b:,并且变量设置为 argv[argc -1]。如果只有一个选项,这很好,但如果有多个选项(即 command -ab fileName),则失败,因为 : 强制用户输入一个选项,但 :: 将使单个选项不强制用户输入一个选项。有什么建议吗?

optind 全局变量让您知道使用了多少个 argv 字符串。所以解决这个问题的一种方法是去掉冒号,并使用像 "ab" 这样的字符串。 这是代码的示例(改编自手册页中的示例):

int main(int argc, char *argv[])
{
    int ch;
    while ((ch = getopt(argc, argv, "ab")) != -1)
    {
        if (ch == 'a')
            printf("Got A\n");
        else if (ch == 'b')
            printf("Got B\n");
        else
            printf("Got confused\n");
    }

    if (optind != argc-1) 
        printf("You forgot to enter the filename\n");
    else
        printf("File: %s\n", argv[optind]);
}

如果您 运行 使用类似

的命令行
./test -ab hello

输出是

Got A
Got B
File: hello