Parsing options with getopt in C
getopt walks argv, handling clustered flags and their arguments.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
int verbose = 0;
int limit = 60;
const char *out = NULL;
int opt;
while ((opt = getopt(argc, argv, "vl:o:")) != -1) {
switch (opt) {
case 'v':
verbose++;
break;
case 'l':
limit = atoi(optarg);
break;
case 'o':
out = optarg;
break;
default:
fprintf(stderr, "usage: %s [-v] [-l N] [-o FILE]\n", argv[0]);
return 1;
}
}
printf("verbose %d limit %d out %s\n", verbose, limit,
out ? out : "(stdout)");
printf("%d positional arguments\n", argc - optind);
return 0;
}
How it works
_POSIX_C_SOURCEmust be defined before the includes to expose getopt.- The option string lists the letters; a colon means it takes a value.
optargholds that value,optindwhere the options ended.
Keywords and builtins used here
NULLbreakcasecharconstdefaultintmainreturnswitchwhile
The run, in numbers
- Lines
- 34
- Characters to type
- 589
- Tokens
- 163
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 103 seconds.
Step 2 of 4 in Program environment, step 2 of 14 in Systems programming.