aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 8fa5e7f99a3afeeaf43dfa9eda70ef861ebbe1eb (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "lib.h"

#define INVERT_T "\x1b[7m"
#define UINVERT_T "\x1b[27m"
#define GREY "\x1b[90m"
#define RESET "\x1b[0m"

int run(char *filename) {
  int tty = isatty(STDOUT_FILENO);

  FILE *fp = fopen(filename, "r+b");

  if (fp == NULL)
    die("fopen");

  if (tty)
    fprintf(stderr, "%s%s%s\r\n", INVERT_T, filename, UINVERT_T);

  int bufsize = 4;
  char *buf;

  buf = malloc(bufsize);
  if (buf == NULL)
    die("malloc");

  double fsize = 0;
  unsigned offset = 0;
  unsigned lc = 0;
  char c;
  while (fread(&c, sizeof(char), 1, fp) > 0) {
    if (fsize == bufsize - 1) {
      bufsize *= 2;

      char *new_buf = realloc(buf, bufsize);
      if (buf == NULL) {
        free(buf);
        die("realloc");
      }

      buf = new_buf;
    }

    if (c == '\n')
      lc++;

    buf[offset++] = c;
    fsize++;
  }
  fclose(fp);

  int lcpad = intlen(lc);

  lc = 0;
  char pc = '\0';
  for (int i = 0; (unsigned)i < offset; i++) {
    c = buf[i];

    if (pc == '\n' || i == 0) {
      lc++;
      int padlen = lcpad - intlen(lc);
      char padding[padlen];
      memset(padding, '0', padlen);
      if (tty)
        fprintf(stderr, "%s%s%d:%s ", GREY, padding, lc, RESET);
    }

    pc = c;
    printf("%c", c);
  }

  char *format = formatBytes(&fsize);

  if (tty)
    fprintf(stderr, "%s%.2f %s%s\r\n", INVERT_T, fsize, format, UINVERT_T);

  return 0;
}

int main(int argc, char *argv[]) {
  if (argc < 2) {
    fprintf(stderr, "usage: catclone <FILE>\n");
    die("args");
  }

  for (int i = 1; i < argc; i++) {
    if (run(argv[i]) != 0)
      die("run");

    if (i + 1 != argc) {
      fprintf(stderr, "\r\n");
    }
  }

  return 0;
}