c - 使用 getopt() 查找目标

标签 c makefile posix

所以我知道您可以使用 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/

相关文章:

c - 静态链接函数在同一台机器上运行时是否具有相同的指针值?

c - 为什么我们需要地址运算符来访问二维字符串元素

c - 用于输入的 fgets()/sscanf 在功能上运行良好。当 fnct 离开并返回时,stdin 中是否有额外的输入/行?

c - 如何获取网络缓冲区并将其传递到需要 C 中的 FILE 的函数中

c - 为什么使用 C printf 格式 "0x"打印 0(零)时没有前导 "%#x"?

linux - makefile 中的 shell 命令

c++ - 如果我在 GCC 中编译和链接不需要的库会怎样?

bash - 提示用户确认

posix - 针对 pthread 函数 pthread_condattr_setclock 链接 NPTL

c - `write(2)` 到本地文件系统的原子性