Created
October 20, 2020 01:06
-
-
Save cflems/8d96dbdd5df31790f9e0ab16470f9001 to your computer and use it in GitHub Desktop.
How to use getopt_long to parse a standard argument list in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <getopt.h> | |
#include <stdio.h> | |
const struct option longopts[] = { | |
{"chdir", no_argument, NULL, 'd'}, | |
{"noclose", no_argument, NULL, 'n'}, | |
{"log-stdout", required_argument, NULL, '1'}, | |
{"log-stderr", required_argument, NULL, '2'}, | |
{0, 0, 0, 0} | |
}; | |
const char* optstring = "dn1:2:"; | |
int main (int argc, char** argv) { | |
int a,b; | |
// &b can be NULL if you don't need it | |
while ((a = getopt_long(argc, argv, optstring, longopts, &b)) != -1) { | |
printf("a: %d\nb: %d\noptarg: %s\n", a, b, optarg); | |
} | |
printf("optind: %d\n", optind); | |
printf("extra: "); | |
while (optind < argc) { | |
printf("%s ", argv[optind++]); | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment