lat/src/lib/file.c

42 lines
606 B
C
Raw Normal View History

2023-04-11 00:14:18 +00:00
#include <stdio.h>
#include <stdlib.h>
#include "file.h"
2023-04-11 03:47:45 +00:00
#include "util.h"
2023-04-11 00:14:18 +00:00
struct filedata readfile(FILE *fp) {
struct filedata f;
f.lc = 0;
f.len = 0;
2023-04-11 16:32:38 +00:00
size_t bufsize = 4;
2023-04-11 00:14:18 +00:00
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;
}