summaryrefslogtreecommitdiff
path: root/src/spons.c
blob: 51bb109b2a291bd6b30d0920ec3ec3b545cbe3a7 (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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "util/versie.h"
#include "io/read_file.h"

static void usage(FILE *f) {
  fprintf(f,
      "Gebruik: spons [-hV] [BESTAND]\n"
      "\n"
      "Zuig standaard invoer op en schrijf naar BESTAND.\n"
      "\n"
      "  -a    Voeg de invoer aan het einde van BESTAND toe, schrijf BESTAND niet over\n"
      "  -h    Toon deze hulptekst\n"
      "  -V    Toon versienummer\n");
}

// Returns pointer to argument array containing the output file name
static char** parse_options(int argc, char **argv, bool *a) {
  int opt;
  while ((opt = getopt(argc, argv, "ahV")) != -1) {
    switch (opt) {
      case 'a':
        *a = true;
        break;

      case 'h':
        usage(stdout);
        exit(0);

      case 'V':
        drukkedoos_print_versie(stdout, "spons");
        exit(0);

      case '?':
        fprintf(stderr, "spons: Ongeldige optie: -%c\n", optopt);
        usage(stderr);
        exit(1);
    }
  }

  return argv + optind;
}

int entry_spons(int argc, char **argv) {
  bool a = false;
  char **args = parse_options(argc, argv, &a);

  FILE *file = stdout;
  if (*args != NULL) {
    file = fopen(*args, a ? "a" : "w");
    if (!file) {
      fprintf(stderr, "spons: Kan doelbestand niet openen\n");
      return 1;
    }
  }

  struct filebuf *fb = stream_to_filebuf(stdin, O_NOALLOWMAP);
  fwrite(fb->buf, 1, fb->sz, file);
  fclose(file);

  free_filebuf(fb);

  return 0;
}