lat/src/lib/file.c

79 lines
1.4 KiB
C
Raw Normal View History

2023-04-11 00:14:18 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2023-04-11 00:14:18 +00:00
2023-04-17 14:23:52 +00:00
#include "types.h"
2023-04-11 03:47:45 +00:00
#include "util.h"
2023-04-11 00:14:18 +00:00
2023-04-17 22:40:17 +00:00
struct filedata readfile(FILE *fp, bool isstdin) {
2023-04-11 00:14:18 +00:00
struct filedata f;
f.lc = 0;
2023-04-17 14:23:52 +00:00
f.buflen = 0;
f.binary = 0;
2023-04-11 00:14:18 +00:00
2023-04-17 14:23:52 +00:00
f.buf = NULL;
f.lines = NULL;
2023-04-17 22:40:17 +00:00
if (isstdin) {
size_t bufsize = 1024;
f.buf = malloc(bufsize);
if (f.buf == NULL)
die("malloc");
char c;
while (fread(&c, 1, 1, fp) > 0) {
if (f.buflen == bufsize - 1) {
bufsize *= 2;
char *new_buf = realloc(f.buf, bufsize);
if (new_buf == NULL)
die("realloc");
f.buf = new_buf;
}
f.buf[f.buflen++] = c;
}
if (f.buflen < bufsize - 1) {
char *new_buf = realloc(f.buf, f.buflen + 1);
if (new_buf == NULL)
die("realloc");
f.buf = new_buf;
}
f.buf[f.buflen] = '\0';
return f;
}
2023-04-13 17:45:15 +00:00
// expects to be at beginning of file
fseek(fp, 0, SEEK_END);
2023-04-17 14:23:52 +00:00
f.buflen = ftell(fp);
2023-04-13 17:45:15 +00:00
fseek(fp, 0, SEEK_SET);
2023-04-17 14:23:52 +00:00
f.buf = malloc(f.buflen);
2023-04-11 00:14:18 +00:00
if (f.buf == NULL)
die("malloc");
2023-04-17 14:23:52 +00:00
if (fread(f.buf, f.buflen, 1, fp) < 0) {
2023-04-13 17:45:15 +00:00
die("fread");
2023-04-11 00:14:18 +00:00
}
// guess if printable
// from https://github.com/sharkdp/content_inspector/blob/master/src/lib.rs
2023-04-17 14:23:52 +00:00
int testlen = f.buflen >= 64 ? 64 : f.buflen;
char *testbuf[testlen];
memcpy(testbuf, f.buf, testlen);
char *result = memchr(testbuf, 0x00, testlen);
if (result) {
f.binary = 1;
} else {
f.binary = 0;
}
2023-04-11 00:14:18 +00:00
return f;
}