summaryrefslogtreecommitdiff
path: root/src/hoofd.c
blob: 0eac51d2c04ac430e06c8c7d9ca87e1052da8f82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <getopt.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#include "util/debug.h"
#include "util/error.h"
#include "util/loop_args.h"
#include "util/versie.h"

#include "io/read_file.h"

int n, c;

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;
}

// TODO: be smarter, hoofd doesn't have to read the whole file in memory (for
// unmappable files)

static void process(struct filebuf *fb, int n, int c) {
  size_t i;
  for (i = 0; i < fb->sz && (n > 0 || n == -1) && (c > 0 || c == -1); i++) {
    if (fb->buf[i] == '\n') {
      if (n != -1) n--;
    }
    if (c != -1) c--;
  }
  fwrite(fb->buf, 1, i, stdout);

  free_filebuf(fb);
}

static int handle(char *arg, bool isstdin) {
  struct filebuf *fb = NULL;

  if (isstdin) {
    fb = stream_to_filebuf(stdin, 0);
    if (fb == NULL) goto err_stdin;
  } else {
    bool isdir = false;
    fb = file_to_filebuf(arg, 0, &isdir);
    if (isdir) goto err_isdir;
    else if (fb == NULL) goto err_file;
  }

  process(fb, n, c);
  return 0;

err_stdin:
  fprintf(stderr, "hoofd: fout bij lezen van standaard invoer\n");
  return 1;

err_file:
  fprintf(stderr, "hoofd: fout bij lezen van bestand\n");
  return 1;

err_isdir:
  fprintf(stderr, "hoofd: bestand '%s' is een mapje\n", arg);
  return 1;
}

int entry_hoofd(int argc, char **argv) {
  n = 10;
  c = -1;
  char **args = parse_options(argc, argv, &n, &c);
  return loop_args(args, handle);
}