From dea256a20d8d771fcce8bd2409bc4b7a9c5081e9 Mon Sep 17 00:00:00 2001 From: Kyle K Date: Sat, 12 Feb 2011 19:45:42 -0600 Subject: add getopt.c --- getopt.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 getopt.c (limited to 'getopt.c') 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 +#include +#include +#include + +/* 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; +} + -- cgit v1.2.3