Parse args in C

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stddef.h> // NULL
#include <stdio.h> // printf
#include <stdlib.h> // atoi
#include <unistd.h> // getopt

int main(int argc, char* argv[])
{
    char* name = NULL;
    int r = 1;
    int opt;
    while ((opt = getopt(argc, argv, "n:r:vh")) != -1) {
        switch (opt) {
            case 'n':
                name = optarg;
                break;
            case 'r':
                r = atoi(optarg);
                break;
            case 'v':
                printf("parse_args v0.0\n");
                break;
            case 'h':
            default:
                print_usage(argv[0]);
                return 0;
        }
    }

    while (r--) {
        printf("hello %s\n", name ? name : "");
    }

    return 0;
}

void print_usage(char* argv0)
{
    printf("Usage: %s [-n <name>] [-r <repeat>] [-v] [-h]\n", argv0);
    printf("Options:\n");
    printf("  -n <name>: Greets <name> by name\n");
    printf("  -r <repeat>: Greets <repeat> times\n");
    printf("  -v: Print out the version\n");
    printf("  -h: Shows this help\n");
}
1
2
3
./app -h
./app -v
./app -n Keven -r 5

References