我已经通读了 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, inoptarg
. 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/