#include #include #include #include #include #include #include #include #include #include #include "util/versie.h" #include "util/error.h" #include "util/debug.h" #include "util/map.h" #include "io/read_file.h" static void usage(FILE *f) { fprintf(f, "Gebruik: toilet [-nchV] [BESTAND]...\n" "\n" "Toon de hoeveelheid regels, woorden en beten for elk BESTAND\n" "\n" " -c Geef het aantal beten weer\n" " -w Geef het aantal woorden weer\n" " -l Geef het aantal regels weer\n" " -h Toon deze hulptekst\n" " -V Toon versienummer\n"); } enum MODE { M_LINES = 1 << 0, M_WORDS = 1 << 1, M_BYTES = 1 << 2, }; // Returns pointer to argument array containing the file names static char** parse_options(int argc, char **argv, int *modeMap) { int opt; while ((opt = getopt(argc, argv, "cwlhV")) != -1) { switch (opt) { case 'c': *modeMap |= M_BYTES; break; case 'w': *modeMap |= M_WORDS; break; case 'l': *modeMap |= M_LINES; break; case 'h': usage(stdout); exit(0); case 'V': drukkedoos_print_versie(stdout); exit(0); case '?': fprintf(stderr, "toilet: Ongeldige optie: -%c\n", optopt); usage(stderr); exit(1); } } return argv + optind; } size_t get_count(enum MODE mode, struct filebuf *fb) { switch (mode) { case M_BYTES: return fb->sz; case M_WORDS: { size_t words = 0; assert(fb->sz >= 0); // (c) Tom Forging for (size_t i = 0; i < (size_t)fb->sz;) { size_t previ = i; while (!isspace(fb->buf[i])) i++; words += i != previ; while (isspace(fb->buf[i])) i++; } return words; } case M_LINES: { size_t lines = 0; size_t i = 0; while (i != fb->sz) { if (fb->buf[i] == '\n') lines++; i++; } // handle case if file does not have trailing newline if (fb->buf[i - 1] != '\n') { lines++; } return lines; } default: assert(false); } } static void process(char *fname, struct filebuf *fb, int modeMap) { for (enum MODE mode = 1; mode <= M_BYTES; mode <<= 1) { if (mode & modeMap) { const size_t count = get_count(mode, fb); printf("%li ", count); } } printf("%s\n", fname); free_filebuf(fb); } // TODO: be smarter, toilet doesn't have to read the whole file in memory (for // unmappable files) int entry_toilet(int argc, char **argv) { int modeMap = 0; char **args = parse_options(argc, argv, &modeMap); if (modeMap == 0) { modeMap = INT_MAX; } if (*args == NULL) { struct filebuf *fb = stream_to_filebuf(stdin, 0); if (fb == NULL) goto err_stdin; process("", fb, modeMap); return 0; } while (*args != NULL) { struct filebuf *fb = NULL; if (!strcmp(*args, "-")) { fb = stream_to_filebuf(stdin, 0); if (fb == NULL) goto err_stdin; *args = ""; // no filename when stdin } else { bool isdir = false; fb = file_to_filebuf(*args, 0, &isdir); if (isdir) goto err_isdir; else if (fb == NULL) goto err_file; } process(*args, fb, modeMap); args++; } return 0; err_stdin: fprintf(stderr, "toilet: fout bij lezen van standaard invoer\n"); return 1; err_file: fprintf(stderr, "toilet: fout bij lezen van bestand\n"); return 1; err_isdir: fprintf(stderr, "toilet: bestand '%s' is een mapje\n", *args); return 1; }