i have program takes in optional arguments. necessary arguments file , integers (1 or more). optional arguments mix of strings , integers.
so correct input on command line be:
./main trace_file 8 12 # (only necessary arguments) ./main –n 3000000 –p page.txt trace_file 8 7 4 # (with optional arguments)
i need integers after trace_file
array. i'm having trouble figuring out how when optional arguments enabled, because integer on command line. push in right direction appreciated, because cannot figure out how this.
edit: far, have parsing arguments this:
for(j=2, k=0; j<argc; j++, k++) { shift += atoi(argv[j]); shiftarr[k] = 32 - shift; bitmaskarr[k] = (int)(pow(2, atoi(argv[j])) - 1) << (shiftarr[k]); entrycnt[k] = (int)pow(2, atoi(argv[j])); }
but work when no optional arguments entered.
i don't see major problems if use reasonably posix-compliant version of getopt()
.
source code (goo.c
)
#include <stdio.h> #include <stdlib.h> #include <unistd.h> /* ./main trace_file 8 12 # (only necessary arguments) ./main –n 3000000 –p page.txt trace_file 8 7 4 # (with optional arguments) */ static void usage(const char *argv0) { fprintf(stderr, "usage: %s [-n number][-p pagefile] trace n1 n2 ...\n", argv0); exit(exit_failure); } int main(int argc, char **argv) { int number = 0; char *pagefile = "default.txt"; char *tracefile; int opt; while ((opt = getopt(argc, argv, "n:p:")) != -1) { switch (opt) { case 'p': pagefile = optarg; break; case 'n': number = atoi(optarg); break; default: usage(argv[0]); } } if (argc - optind < 3) { fprintf(stderr, "%s: few arguments\n", argv[0]); usage(argv[0]); } tracefile = argv[optind++]; printf("trace file: %s\n", tracefile); printf("page file: %s\n", pagefile); printf("multiplier: %d\n", number); (int = optind; < argc; i++) printf("processing number: %d (%s)\n", atoi(argv[i]), argv[i]); return 0; }
compilation
$ gcc -o3 -g -std=c11 -wall -wextra -wmissing-prototypes -wstrict-prototypes \ > -wold-style-definition -werror goo.c -o goo
example runs
$ ./goo trace_file 8 12 trace file: trace_file page file: default.txt multiplier: 0 processing number: 8 (8) processing number: 12 (12) $ ./goo -n 3000000 -p page.txt trace_file 8 7 4 trace file: trace_file page file: page.txt multiplier: 3000000 processing number: 8 (8) processing number: 7 (7) processing number: 4 (4) $