Read file in one read

This commit is contained in:
Shav Kinderlehrer 2023-04-13 13:45:15 -04:00
parent 03d4f4fddf
commit f1892da51e

View File

@ -12,32 +12,21 @@ struct filedata readfile(FILE *fp) {
f.len = 0; f.len = 0;
f.binary = 0; f.binary = 0;
size_t bufsize = 4; // expects to be at beginning of file
f.buf = malloc(bufsize); fseek(fp, 0, SEEK_END);
f.len = ftell(fp);
fseek(fp, 0, SEEK_SET);
f.buf = malloc(f.len);
if (f.buf == NULL) if (f.buf == NULL)
die("malloc"); die("malloc");
char c; if (fread(f.buf, f.len, 1, fp) < 0) {
while (fread(&c, sizeof(char), 1, fp) > 0) { die("fread");
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;
} }
f.lc = 1000;
// guess if printable // guess if printable
// from https://github.com/sharkdp/content_inspector/blob/master/src/lib.rs // from https://github.com/sharkdp/content_inspector/blob/master/src/lib.rs
int testlen = f.len >= 64 ? 64 : f.len; int testlen = f.len >= 64 ? 64 : f.len;