#include #include #include #include #include #include #include #include #include "util/debug.h" #include "util/error.h" #include "util/loop_args.h" #include "util/versie.h" #include "io/read_file.h" static int gn, gc; static void usage(FILE *f) { fprintf(f, "Gebruik: hoofd [-nchV] [BESTAND]...\n" "\n" "Toon de eerste 10 regels van elk BESTAND naar standaard uitvoer\n" "\n" " -n AANTAL Aantal regels om weer te geven\n" " -c AANTAL Aantal karakters om weer te geven\n" " -h Toon deze hulptekst\n" " -V Toon versienummer\n"); } // Returns pointer to argument array containing the file names static char** parse_options(int argc, char **argv, int *n, int *c) { int opt; while ((opt = getopt(argc, argv, "n:c:hV")) != -1) { switch (opt) { case 'c': *c = atoi(optarg); *n = -1; break; case 'n': *c = -1; *n = atoi(optarg); break; case 'h': usage(stdout); exit(0); case 'V': drukkedoos_print_versie(stdout); exit(0); case '?': fprintf(stderr, "hoofd: Ongeldige optie: -%c\n", optopt); usage(stderr); exit(1); } } return argv + optind; } static int process(char *fname, bool isstdin) { FILE *stream = NULL; if (isstdin) { stream = stdin; } else { stream = fopen(fname, "rb"); } if (gc != -1) { char *buf = calloc(gc, 1); if (fread(buf, 1, gc, stream) != (unsigned int)gc) { printf("hoofd: fout bij lezen uit bestand '%s'\n", fname); exit(1); } if (fwrite(buf, 1, gc, stdout) != (unsigned int)gc) { printf("hoofd: fout bij schrijven naar stanaard uitvoer\n"); exit(1); } free(buf); goto done; } assert(gn >= 0); int n = gn; char *line = NULL; size_t linen = 0; ssize_t nread = 0; while ((errno = 0, nread = getline(&line, &linen, stream)) != -1) { if (n == 0) break; printf("%s", line); n--; } free(line); if (errno != 0) { printf("hoofd: fout bij lezen uit bestand '%s'\n", fname); exit(1); } done: if (!isstdin) { fclose(stream); } return 0; } int entry_hoofd(int argc, char **argv) { gn = 10, gc = -1; char **args = parse_options(argc, argv, &gn, &gc); return loop_args(args, process); }