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);
}
}
}
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
I'm running a Mac with OS X using C language.
Try this solution. It works for me. Consider option 'z' as option with optional argument.
Here are some examples:
Maybe I'm misunderstanding the question. I'm reading it as though the user wants to over ride getopt's default error handling. If that is the case, shouldn't there be a : in the beginning of their OPT_LIST? I think the code above is good, however, I think it will still print
To surpress that, don't we need a : at the beginning of the OPT_LIST? For example, changing this:
to this:
Correct me if I'm wrong.
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.
https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html
In fact, POSIX.1-2008, section 12.2, "Utility Syntax Guidelines", explicitly forbids this feature:
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02
According to the getopt documentation, it will return
:
if an option with an argument does not have one. It also setsoptopt
with the matching argument.Therefore, use: