gpt4 book ai didi

c - Getopt - 需要输入

转载 作者:行者123 更新时间:2023-11-30 15:04:17 27 4
gpt4 key购买 nike

我要做一个名为:

的程序
>./program [-p] [-h] [-n <number>] <file>

我的 getopt 工作正常,但我需要以某种方式获取文件,我尝试使用 optind但是<file>可以在任何标志之前给出。可能的调用是:

>./program bomber.txt
>./program bomber.txt -n 2 -p
>./program -h bomber.txt -n 4
>./program -p -n 3 bomber.txt

最佳答案

您可以在 https://linux.die.net/man/3/getopt 找到 getopt 的文档。

您的问题的实际答案在以下段落中

By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end. Two other modes are also implemented. If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered. If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.) The special argument "--" forces an end of option-scanning regardless of the scanning mode.

关键点是 getopt 排列命令行。当您完成解析所有选项后,argv[optind] 将引用强制文件名。

如果命令行中不存在文件名,optind 将等于 argc

关于c - Getopt - 需要输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349030/

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