Getopt 可选参数? [英] Getopt optional arguments?
问题描述
我有一个程序,您可以在其中输入一个选项-d
然后不管你是否在选项后提供一个非可选参数,做一些事情.
这是我的代码:
I have a program where you enter an option
-d
and then whether or not you supply a non-optional argument after the option, do something.
Heres my code:
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#define OPT_LIST "d::"
int main (int argc, char *argv[])
{
int c;
char string[] = "blah";
while ((c = getopt (argc, argv, OPT_LIST)) != -1)
{
switch (c)
{
case 'd':
printf("%s\n", optarg);
break;
case '?':
fprintf(stderr, "invalid option\n");
exit(EXIT_FAILURE);
}
}
}
因此,如果您在选项后输入非可选参数,则会打印该参数.但是如果用户不提供非可选参数,我希望它打印出字符字符串"(这就是为什么我将双冒号放在OPT_LIST).但我不知道如何做到这一点,所以任何帮助将不胜感激.
So if you enter a non-optional argument after the option, it prints the argument. But I want it to print out the char "string" if the user doesn't supply a non-optional argument (this is why I put the double colon in the OPT_LIST). But I'm not sure how to do this so any help would be greatly appreciated.
以下是我运行程序时发生的情况:
Heres what happens when I run the program:
user:desktop shaun$ ./arg -d hello
hello
user:desktop shaun$ ./arg -d
./arg: option requires an argument -- d
invalid option
我使用 C 语言在 OS X 上运行 Mac.
I'm running a Mac with OS X using C language.
推荐答案
选项的可选值"功能只是 GNU libc 扩展,POSIX 不需要,并且可能只是 Mac OS 附带的 libc 未实现十.
The "optional value of an option" feature is only a GNU libc extension, not required by POSIX, and is probably simply unimplemented by the libc shipped with Mac OS X.
options 参数是一个字符串,用于指定对该程序有效的选项字符.此字符串中的选项字符后可以跟一个冒号 (‘:’) 以指示它需要一个必需的参数.如果选项字符后跟两个冒号(‘::’),则其参数是可选的;这是一个 GNU 扩展.
The options argument is a string that specifies the option characters that are valid for this program. An option character in this string can be followed by a colon (‘:’) to indicate that it takes a required argument. If an option character is followed by two colons (‘::’), its argument is optional; this is a GNU extension.
https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html
实际上,POSIX.1-2008 的第 12.2 节实用程序语法指南"明确禁止此功能:
In fact, POSIX.1-2008, section 12.2, "Utility Syntax Guidelines", explicitly forbids this feature:
准则 7:选项参数不应该是可选的.
Guideline 7: Option-arguments should not be optional.
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02
这篇关于Getopt 可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!