Skip to content

Instantly share code, notes, and snippets.

@cflems
Created October 20, 2020 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cflems/8d96dbdd5df31790f9e0ab16470f9001 to your computer and use it in GitHub Desktop.
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.
#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