typestar

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

  1. _POSIX_C_SOURCE must be defined before the includes to expose getopt.
  2. The option string lists the letters; a colon means it takes a value.
  3. optarg holds that value, optind where the options ended.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Program environment, step 2 of 14 in Systems programming.

← Previous Next →