Alesfatalis Alesfatalis - 21 days ago 9
C Question

getopt_long() option with optional argument

I am trying to create a option with an optional argument using getopt_long().

Here is my code:


static struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"debug", no_argument, NULL, 'd'},
{"config", optional_argument, NULL, 'c'},
{NULL, 0, NULL, 0}
};

while ((ch = getopt_long(argc, argv, "hdc::", long_options, NULL)) != -1) {
// check to see if a single character or long option came through
switch (ch) {
case 'h':
opt.help = true;
break;
case 'd':
opt.debug = true;
break;
case 'c':
printf("C-Option: %s\n", optarg);
if (optarg != NULL) {
opt.configFile = optarg;
}
break;
}
}


I am trying to make the argument for
-c
optional so you can run the program with these options:

-c test.cfg
-->
optarg = "test.cfg"


-c
-->
optarg = null


If I set
c::
than
optarg
is always
null
.

If I set
c:
than I get an error:
option requires an argument -- 'c'


What did I wrong? Is there any other options I can set?

Answer

From the man pages:

If the option has an optional argument, it must be written directly after the option character if present.

Your code works as expected:

./a.out -c some_option --> "C-Option: (null)"
./a.out -csome_option --> "C-Option: some_option"
Comments