0Pricing
C Academy · Lesson

Parsing Options

Handle flags.

Options vs positional arguments

Command-line arguments come in two flavors. Positional arguments are values like filenames. Options (also called flags) start with a dash, like -v or --help.

This lesson shows how to detect and handle flags manually.

#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (argv[i][0] == '-')
            printf("option: %s\n", argv[i]);
        else
            printf("value:  %s\n", argv[i]);
    }
    return 0;
}

Detecting a flag

To check for a specific flag, compare each argument with strcmp.

Here we set a boolean when we see -v for verbose mode.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int verbose = 0;
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0)
            verbose = 1;
    }
    printf("verbose = %d\n", verbose);
    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