aboutsummaryrefslogtreecommitdiff
path: root/src/lib/file.c
blob: b0cd283b22789c74be94f527f38e251175405cf5 (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
#include <stdio.h>
#include <stdlib.h>

#include "file.h"
#include "util.h"

struct filedata readfile(FILE *fp) {
  struct filedata f;

  f.lc = 0;
  f.len = 0;

  unsigned bufsize = 4;

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

  char c;
  while (fread(&c, sizeof(char), 1, fp) > 0) {
    if (f.len == bufsize - 1) {
      bufsize *= 2;

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

      f.buf = new_buf;
    }

    if (c == '\n') {
      f.lc++;
    }

    f.buf[f.len++] = c;
  }

  return f;
}