summaryrefslogtreecommitdiffstats
path: root/getopt.c
blob: 1da0882930658738790f5b44164ab1d66e469b01 (plain)
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
45
46
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* getopt() external variables */
extern char *optarg;
extern int optind, opterr, optopt;

int main(int argc, char **argv)
{
    int opt;
    int fname_f = 0, random_f = 0; /* options' flags */
    char *fname_a = NULL;

    while ((opt = getopt(argc, argv, "o::c")) != -1)
    {
        switch (opt)
        {
        case 'o':
            fname_f = 1;
#if 0       /* optional args to an option can only be of this format: -ofile.txt */
            if (optarg)
                fname_a = strdup(optarg);
#endif      /* we will check optind in the end and that should be the filename */
            break;
        case 'c':
            random_f = 1;
            break;
        default: /* '?' */
            fprintf(stderr, "usage: %s [-o fname] [-c]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    if (argv[optind])
        fname_a = strdup(argv[optind]);

    printf("fname_f = %d\nfname_a = %s\nrandom_f = %d\noptind = %d\n", fname_f,
           fname_a, random_f, optind);

    printf("optind = %s\n", argv[optind]);

    return 0;
}