getopt
Standard option parsing.
What is getopt?
getopt is a POSIX function that parses single-character options for you, following standard Unix conventions.
It lives in <unistd.h> and removes most of the boilerplate of manual flag parsing.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "v")) != -1) {
if (opt == 'v') printf("verbose on\n");
}
return 0;
}The optstring
The third argument to getopt is the optstring: a list of valid option letters.
"abc" means -a, -b, and -c are all accepted boolean flags.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "abc")) != -1) {
printf("saw option -%c\n", opt);
}
return 0;
}