summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKyle K <kylek389@gmail.com>2011-02-12 19:45:42 -0600
committerKamil Kaminski <kamilkss@gmail.com>2011-02-12 19:45:42 -0600
commitdea256a20d8d771fcce8bd2409bc4b7a9c5081e9 (patch)
treebacf02603fa84af97266e18e5e5308cb9b15177f
parentdbe61956e0b4235238c225df58383141337bc2d2 (diff)
downloadsandbox-dea256a20d8d771fcce8bd2409bc4b7a9c5081e9.tar.gz
sandbox-dea256a20d8d771fcce8bd2409bc4b7a9c5081e9.tar.bz2
sandbox-dea256a20d8d771fcce8bd2409bc4b7a9c5081e9.zip
add getopt.c
-rw-r--r--Makefile3
-rw-r--r--getopt.c46
2 files changed, 48 insertions, 1 deletions
diff --git a/Makefile b/Makefile
index 273a07b..4a52efa 100644
--- a/Makefile
+++ b/Makefile
@@ -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;
+}
+