summaryrefslogtreecommitdiffstats
path: root/getopt.c
diff options
context:
space:
mode:
Diffstat (limited to 'getopt.c')
-rw-r--r--getopt.c46
1 files changed, 46 insertions, 0 deletions
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;
+}
+