pud*_*ter 8 c arguments getopt optional option
我有一个程序,你输入一个选项-d
,然后在选项
后是否提供非可选参数,做一些事情.
继承我的代码:
#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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果在选项后输入非可选参数,则会打印参数.但是如果用户没有提供非可选参数,我希望它打印出char"string"(这就是为什么我把双冒号放在OPT_LIST中).但我不知道如何做到这一点,所以任何帮助将不胜感激.
下面是我运行程序时会发生什么:
user:desktop shaun$ ./arg -d hello
hello
user:desktop shaun$ ./arg -d
./arg: option requires an argument -- d
invalid option
Run Code Online (Sandbox Code Playgroud)
我正在使用C语言运行带有OS X的Mac.
Del*_*ani 15
"选项的可选值"功能只是一个GNU libc扩展,POSIX不需要,并且可能只是由Mac OS X附带的libc实现.
options参数是一个字符串,它指定对此程序有效的选项字符.此字符串中的选项字符后面可以跟冒号(':'),表示它需要一个必需的参数.如果选项字符后跟两个冒号('::'),则其参数是可选的; 这是一个GNU扩展.
https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html
事实上,POSIX.1-2008第12.2节"实用语法指南"明确禁止此功能:
准则7:选项参数不应是可选的.
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02
根据getopt文档,:
如果带参数的选项没有一个,它将返回.它还optopt
使用匹配参数进行设置.
因此,使用:
int main (int argc, char *argv[])
{
int c;
while ((c = getopt (argc, argv, "d:f:")) != -1)
{
switch (c)
{
case 'd':
case 'f':
printf("option -%c with argument '%s'\n", c, optarg);
break;
case ':':
switch (optopt)
{
case 'd':
printf("option -%c with default argument value\n", optopt);
break;
default:
fprintf(stderr, "option -%c is missing a required argument\n", optopt);
return EXIT_FAILURE;
}
break;
case '?':
fprintf(stderr, "invalid option: -%c\n", optopt);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)