我有一个程序,你可以输入选项-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);
}
}
}
如果在选项后输入非可选参数,则会打印该参数。但是如果用户未提供非可选参数,则我希望它能打印出字符“string”(这就是为什么我在OPT_LIST中放置双冒号的原因)。但我不确定如何实现这一点,所以任何帮助都将不胜感激。当我运行程序时,发生了什么:
user:desktop shaun$ ./arg -d hello
hello
user:desktop shaun$ ./arg -d
./arg: option requires an argument -- d
invalid option
我正在使用C语言在OS X操作系统下的Mac电脑上运行。
printf("%s\n", string)
? - user529758fprintf(stderr, "invalid option\n");
所在的位置,那么它就会执行相同的操作。 - user529758./arg: option requires an argument -- d
这个错误信息。你有什么办法可以消除这个错误吗? - pudumastergetopt()
来打印诊断信息。 - user529758