diff options
-rw-r--r-- | Makefile | 3 | ||||
-rw-r--r-- | getopt.c | 46 |
2 files changed, 48 insertions, 1 deletions
@@ -1,4 +1,5 @@ -BINS = ascii class depipe_strings dup fpipe pipe realloc strpbrk strsep tokenizer +BINS = ascii class depipe_strings dup fpipe pipe realloc strpbrk strsep \ + tokenizer getopt CC = gcc DBGFLAGS = -g -O0 ifdef DEBUG diff --git a/getopt.c b/getopt.c new file mode 100644 index 0000000..1da0882 --- /dev/null +++ b/getopt.c @@ -0,0 +1,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; +} + |