0Pricing
C Academy · Lesson

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;
}

All lessons in this course

  1. argc and argv
  2. Parsing Options
  3. getopt
  4. Building a CLI Tool
← Back to C Academy