gpt4 book ai didi

c - getopt 只接受一个参数

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:10 25 4
gpt4 key购买 nike

我有一个关于 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

关于c - getopt 只接受一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49502325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com