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?