/* Name: arg.c Purpose: provides support for processing command-line arguments Author: Bill Slough */ #include #include #include #include #include "util.h" #include "arg.h" /* Process the arguments from a given command line, checking for errors, summarizing the results in an args_t structure */ void process_args(int argc, char *argv[ ], struct args_t *argument) { int opt; int nr_non_options; int countFlag; int repeatedFlag; int notRepeatedFlag; /* initializations... */ countFlag = 0; repeatedFlag = 0; notRepeatedFlag = 0; opterr = 0; /* we are responsible for error diagnostics */ while ((opt = getopt (argc, argv, "cdu")) != -1) switch (opt) { case 'c': countFlag = 1; break; case 'd': repeatedFlag = 1; break; case 'u': notRepeatedFlag = 1; break; case '?': fprintf (stderr, "%s: illegal option `-%c'.\n", argv[0], optopt); display_usage(argv[0]); default: abort(); } /* Was just one option provided? */ if (countFlag + repeatedFlag + notRepeatedFlag > 1) { fprintf(stderr, "%s: conflicting options\n", argv[0]); display_usage(argv[0]); } /* set the appropriate option */ if (countFlag == 1) argument->option = 'c'; else if (repeatedFlag == 1) argument->option = 'd'; else if (notRepeatedFlag == 1) argument->option = 'u'; else argument->option = 'n'; /* how many non-options appear on the command line? */ nr_non_options = argc - optind; if (nr_non_options == 0) /* none: no input file name was given */ argument->inputFile = NULL; else if (nr_non_options == 1) { /* one: presumably, the name of an input file */ argument->inputFile = (char *) safe_malloc(strlen(argv[optind]) + 1); strcpy(argument->inputFile, argv[optind]); } else { /* two or more: violates the syntax for pmuniq */ fprintf(stderr, "%s: too many arguments\n", argv[0]); display_usage(argv[0]); } } /* Tell the user how to use this program */ void display_usage(char *pname) { fprintf(stderr, "usage: %s [-c | -d | -u] [input]\n", pname); exit(EXIT_FAILURE); }