summaryrefslogtreecommitdiffhomepage
path: root/tools/xpcat/xpcat.c
blob: e39babcb58caf8e976ed83ef7310d2ce5d92aed0 (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void
usage(const char *program)
{
  printf("Usage: %s -o outputfile FILE...\n", program);
}

int
main(int argc, char *argv[])
{
  int i, ch;
  const char *output = NULL;
  FILE *infile = NULL;
  FILE *outfile = NULL;

  if (argc < 4) {
    usage(argv[0]);
    return EXIT_FAILURE;
  }

  for (i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-o") == 0) {
      i++;
      if (i < argc)
        output = argv[i];
      else {
        usage(argv[0]);
        return EXIT_FAILURE;
      }
    }
  }

  if (output) {
    outfile = fopen(output, "wb");
    if (!outfile) {
      fprintf(stderr, "[ERROR] unable to open output file: %s\n", output);
      return EXIT_FAILURE;
    }
    setbuf(outfile, NULL);

    for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "-o") == 0) {
        i++;
        continue;
      }

      infile = fopen(argv[i], "rb");
      if (!infile) {
        fprintf(stderr, "[ERROR] unable to open input file: %s\n", argv[i]);
        return EXIT_FAILURE;
      }
      setbuf(infile, NULL);

      while ((ch = getc(infile)) != EOF) {
        if (putc(ch, outfile) == EOF) {
          fprintf(stderr, "[ERROR] error writing output file: %s\n", output);
          return EXIT_FAILURE;
        }
      }

      fclose(infile);
    }
  }

  fclose(outfile);
  return EXIT_SUCCESS;
}

/* vim: set ts=2 sts=2 sw=2 et: */