/** * getopt-experiment.c * A simple toolbox for experimenting with getopt. * Samuel A. Rebelsky. * */ // +---------+------------------------------------------------------- // | Headers | // +---------+ #include #include #include // +---------+------------------------------------------------------- // | Helpers | // +---------+ /** * Print an array of strings. */ void fprintstrings (FILE *port, char *strings[], int nstrings) { if (0 == nstrings) { fprintf (port, "[]"); } // if no strings else { fprintf (port, "[\"%s\"", strings[0]); for (int i = 1; i < nstrings; i++) { fprintf (port, ", \"%s\"", strings[i]); } // for fprintf (port, "]"); } // if (nstrings > 0) } // fprintstrings /** * Print getopt status. */ void status (FILE *port, int opt, char *argv[], int argc) { fprintf (port, "Status\n"); fprintf (port, " opt: '%c' (%d)\n", opt, opt); fprintf (port, " optopt: '%c' (%d)\n", optopt, optopt); fprintf (port, " optind: %d\n", optind); fprintf (port, " optarg: \"%s\"\n", optarg); fprintf (port, " argv: "); fprintstrings (port, argv, argc); fprintf (port, "\n\n"); } // status // +------+---------------------------------------------------------- // | Main | // +------+ int main (int argc, char *argv[]) { int opt = 0; while ((opt = getopt (argc, argv, "abc:d:ef?")) != -1) { switch (opt) { case 'a': break; case 'b': break; case 'c': break; case 'd': break; case 'e': fprintf (stderr, "Flipping opterr.\n"); opterr = ! opterr; break; case 'f': break; default: fprintf (stderr, "Invalid argument: %c\n", optopt); fprintf (stderr, " Usage: %s [-a] [-b] [-c arg] [-d arg] [-e] [-f [arg]] file0 file1 ...\n", argv[0]); break; } // switch status (stderr, opt, argv, argc); } // while fprintf (stderr, "DONE PROCESSING OPTIONS\n"); status (stderr, opt, argv, argc); fprintf (stderr, "Remaining strings: "); fprintstrings (stderr, argv+optind, argc-optind); fprintf (stderr, "\n"); exit (EXIT_SUCCESS); } // main