Skip to content

Instantly share code, notes, and snippets.

@ilansmith
Last active October 18, 2018 23:21
Show Gist options
  • Save ilansmith/a2000218aa0a25c4fb9475b65d253cda to your computer and use it in GitHub Desktop.
Save ilansmith/a2000218aa0a25c4fb9475b65d253cda to your computer and use it in GitHub Desktop.
getopt() for optional argument
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#define ALIGN_OPTIONAL_ARGUMENT(_argc, _argv, _optstring, _optarg, _optind) \
do { \
if (!(_optarg) && (_optind) < (_argc) && \
(((_argv)[(_optind)][0] != '-') || \
!strchr(_optstring, (_argv)[(_optind)][1]))) { \
(_optarg) = (_argv)[(_optind)++]; \
} \
} while (0)
int main(int argc, char **argv)
{
char *optstring = "a:b::c";
char o;
while ((o = getopt(argc, argv, optstring)) != -1) {
switch (o) {
case 'b':
ALIGN_OPTIONAL_ARGUMENT(argc, argv, optstring, optarg,
optind);
case 'a':
case 'c':
printf("-%c got optarg: %s\n", o,
optarg ? optarg : "N/A");
break;
}
}
return 0;
}
@ilansmith
Copy link
Author

ilansmith commented Oct 18, 2018

$ gcc my_getopt.c

$ ./a.out -b    -x
-b got optarg: -x

$ ./a.out -b    -c
-b got optarg: N/A
-c got optarg: N/A

$ ./a.out -b    -a
-b got optarg: N/A
./a.out: option requires an argument -- 'a'

$ ./a.out -b    -a x
-b got optarg: N/A
-a got optarg: x

$ ./a.out -b    -x x
-b got optarg: -x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment