#include #include #include // for getopt #include #include "scolor.h" struct arguments { int nfacts; char print_count, green, numbers, red; }; struct arguments arguments = {1, 0, 0, 0, 0}; char *facts[] = { "Goats like the leaf from alfalfa, and try to waste all the stems", "Goats like to eat raspberry leaves", "A goat bit my pants last night", "Goat normally have horns, and all mine have horns." }; int factcount = 4; void print_usage(const char *progname) { fprintf(stderr, "Usage: %s [options]\n" "Options:\n" " -c Show how many goat facts we have\n" " -n Number of facts to display\n" " -g Print facts in green\n" " -l Print line numbers on each fact\n" " -r Print line numbers in red\n", progname); } int main(int argc, char **argv) { int opt; while ((opt = getopt(argc, argv, "cn:glr")) != -1) { switch (opt) { case 'c': arguments.print_count = 1; break; case 'n': arguments.nfacts = atoi(optarg); break; case 'g': arguments.green = 1; break; case 'l': arguments.numbers = 1; break; case 'r': arguments.red = 1; break; default: print_usage(argv[0]); exit(EXIT_FAILURE); } } if (arguments.print_count) { printf("We have %d facts\n", factcount); return 0; } if (arguments.nfacts > factcount) arguments.nfacts = factcount; for (int i = 0; i < arguments.nfacts; i++) { if (arguments.numbers) { if (arguments.red) printf(RED("%d: "), i + 1); else printf("%d: ", i + 1); } if (arguments.green) printf(GREEN("%s\n"), facts[i]); else puts(facts[i]); } return 0; }