Parsing Command Line Arguments in C

The getopt API can help us parse command line arguments in C.

Its included with C so we only need to “#include <unistd.h> at the top and then configure how we want to parse the arguments.

The getopt function takes argc and argv as initial arguments, and then we specify in the third what characters to use as options. E.g. If we specify “a” then the user can specify an option “-a” on the command line.

getopt(argc, argv, "a")
./some_program -a

If we specify “abc”, then the user can specify -a, -b or -c on the command line. E.g.

getopt(argc, argv, "abc")
./some_program -a -b -c

If we want to specify a value for an argument then we add a colon after the character. E.g.

getopt(argc, argv, "a:b:c:")
./some_program -a "argument for a" -b "argument for b" -c "argument for c"

The getopt function returns either the character of the option it has just parsed, or if there are no arguments then it returns -1. The specified value given with each argument is stored in optarg. We combine this with a switch case to act on the arguments given.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h> // getOpt functions

int main(int argc, char *argv[]) {

    printf("Running parser test\n"); fflush(stdout);

    int opt; // i.e. option

    int input_number = 0;
    int output_number = 0;
    bool switch_on = false;
    
    while ((opt = getopt(argc, argv, "i:o:s")) != -1) {
        switch (opt) {
            case 'i':
                input_number = atoi(optarg);
                break;
            case 'o': 
                output_number = atoi(optarg);
                break;
            case 's':
                switch_on = true;
                break;
            default:
                fprintf(stderr, "Usage: %s [-i] [input number] [-o] [output number] [-s]\n", argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    printf("The user specified %d as the input number\n", input_number);
    printf("The user specified %d as the output number\n", output_number);
    printf("The switch is %d\n", switch_on);

    return 0;
}