gpt4 book ai didi

c - 使用 getopt() 查找目标

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:56 24 4
gpt4 key购买 nike

所以我知道您可以使用 getopt() 来查找选项参数,但是 argv 数组中的其他内容(例如目标)呢?有没有办法使用 getopt() 来做到这一点?翻阅手册页,我什么也没看到……也许我错过了。

最佳答案

为此使用optarg(它是一个字符串,使用sscanf 从中读取)。

引用自man 3 getopt:

   optstring is a string containing the legitimate option characters.  If such a character is followed by a colon, the option requires an argument, so getopt()
places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an
optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in
optarg, otherwise optarg is set to zero. This is a GNU extension. If optstring contains W followed by a semicolon, then -W foo is treated as the long
option --foo. (The -W option is reserved by POSIX.2 for implementation extensions.) This behavior is a GNU extension, not available with libraries before
glibc 2.

如果您有额外的参数(à la cp -l file1 file2),它们将保留在 argv 的最新位置上,从 optind 开始>.

PS:man 页面末尾还有一个示例。

关于c - 使用 getopt() 查找目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19746602/

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