Skip to content

Instantly share code, notes, and snippets.

@PJayB
Created January 21, 2020 17:11
Show Gist options
  • Select an option

  • Save PJayB/7b7f3cd37c951914fd497c1b7f8af194 to your computer and use it in GitHub Desktop.

Select an option

Save PJayB/7b7f3cd37c951914fd497c1b7f8af194 to your computer and use it in GitHub Desktop.
char getopt_long_2(int argc, char** argv, const char* optString, const struct option* longOpts, int* optIndex) {
int c = getopt_long(argc, argv, optString, longOpts, optIndex);
if (c == -1) {
// No more options
return c;
}
if (c == 0) {
// Long option was specified -- find the short option
c = longOpts[*optIndex].val;
} else {
// Short option was specified -- find the long option
for (const struct option* i = longOpts; i->name != nullptr; ++i) {
if (c == i->val) {
*optIndex = i - longOpts;
break;
}
}
}
// If the parameter requires an optional argument then
// we need to work around some BS behavior of getopt_long here:
// it expects optional arguments to be specified with =,
// whereas it does not specify this requirement in literally
// any another case >_>
if (longOpts[*optIndex].has_arg == optional_argument &&
optarg == nullptr &&
optind < argc &&
argv[optind][0] != '-') {
optarg = argv[optind++];
}
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment