c - 函数 getopt() 的变量 optarg

标签 c getopt

我已经通读了 documentation for the function getopt() ,但我没有找到明确的解释,尤其是关于变量 optarg 的解释。我找不到任何其他来源来明确和清楚地解释有关 optarg 的一般信息。我的问题如下:

  • 什么是optarg
  • optarg 如何获取它的值?
  • 文档中提到冒号改变了optarg的值;这是如何运作的?

文档中有如何使用 optarg 的示例,但我更感兴趣的是对变量本身的清晰详尽的解释。

最佳答案

man page说,(强调我的)

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. [...]

下面给出的代码片段显示了用法。

while ((opt = getopt(argc, argv, "nt:")) != -1) {
    switch (opt) {
    case 'n':
        flags = 1;
        break;
    case 't':
        nsecs = atoi(optarg);
        tfnd = 1;
        break;
    default: /* '?' */
        fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }
}

详细来说,通过查看语法 "nt:" 我们可以理解选项 n 不需要任何参数,但选项 t将有以下论点。因此,当找到选项 t 时,相应的参数将存储到 optarg 中,并且可以通过访问 optarg 来检索。

所以,基本上,getopt() 将返回选项optarg 将返回提供的参数该选项,如果有的话。

如果二进制文件像 ./a.out -t 30 一样运行,那么当 getopt() 返回 t 时,optarg 将持有一个指向包含 30(不是 int,请注意)的 string 的指针。

关于c - 函数 getopt() 的变量 optarg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40254116/

相关文章:

c - getopt() 行为异常

c - 汇编语言中的内存地址是一次性静态分配的吗?

c - 在 Windows 中,如何在 C 中跟踪子进程读取和写入的文件?

bash - getopts 在没有命令时打印帮助。行参数匹配

c - Getopt - 需要输入

php - 使用 getopt 捕获意外选项

c - C 中数据类型的大小是否取决于操作系统?

c - C中主要函数的风格

c - 在 Clion 中链接 libgit2 不起作用

c - C中通过getopt解析命令行参数