libflint/src/lfinput.c

124 lines
2.4 KiB
C
Raw Normal View History

2021-12-10 20:41:36 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#ifdef __linux__
2022-03-28 17:52:16 +00:00
2021-12-10 20:41:36 +00:00
#include <bsd/stdlib.h>
2022-03-28 17:52:16 +00:00
2021-12-10 20:41:36 +00:00
#endif
#include "lfinput.h"
2021-12-10 20:41:36 +00:00
2023-05-03 21:26:58 +00:00
static FILE* open_file(const char *path, size_t *fsz) {
2021-12-10 20:41:36 +00:00
FILE *fp = NULL;
fp = fopen(path, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to open %s. Returning NULL\n", path);
return NULL;
}
fseek(fp, 0, SEEK_END);
2023-05-03 21:26:58 +00:00
*fsz = ftell(fp);
2021-12-10 20:41:36 +00:00
rewind(fp);
2023-05-03 21:26:58 +00:00
return fp;
}
2023-05-03 21:46:38 +00:00
char *get_binary(const char *path, size_t *fsz) {
FILE *fp = open_file(path, fsz);
2023-05-03 21:26:58 +00:00
if (fp == NULL) {
return NULL;
}
char *buf = NULL;
2023-05-03 21:46:38 +00:00
buf = malloc(*fsz);
2023-05-03 21:26:58 +00:00
if (buf == NULL) {
fprintf(stderr, "Failed to malloc buf. Returning NULL\n");
fclose(fp);
return NULL;
}
2023-05-03 21:46:38 +00:00
fread(buf, 1, *fsz, fp);
2023-05-03 21:26:58 +00:00
fclose(fp);
return buf;
}
char *get_input(const char *path) {
size_t fsz = 0;
FILE *fp = open_file(path, &fsz);
if (fp == NULL) {
return NULL;
}
2022-03-28 17:52:16 +00:00
char *buf = NULL;
2021-12-10 20:41:36 +00:00
buf = malloc(fsz + 1);
if (buf == NULL) {
fprintf(stderr, "Failed to malloc buf. Returning NULL\n");
fclose(fp);
return NULL;
}
fread(buf, 1, fsz, fp);
buf[fsz] = '\0';
fclose(fp);
return buf;
}
2021-12-10 22:33:37 +00:00
char **split(char *s, size_t *lsz, const char *delim) {
2021-12-10 20:41:36 +00:00
char **lines = NULL;
char *t = strtok(s, delim);
size_t n = 0;
while (t != NULL) {
lines = realloc(lines, sizeof(char *) * ++n);
if (lines == NULL) {
fprintf(stderr, "Failed to realloc lines buffer. Returning NULL\n");
free(s);
return NULL;
}
lines[n - 1] = t;
t = strtok(NULL, delim);
}
*lsz = n;
return lines;
}
char **get_lines(const char *path, size_t *lsz) {
return split(get_input(path), lsz, "\n");
}
int *get_ints(const char *path, size_t *sz) {
char **lines = get_lines(path, sz);
int *i = malloc(sizeof(int) * *sz);
for (size_t idx = 0; idx < *sz; idx++) {
int n;
const char *errstr;
2022-03-28 17:52:16 +00:00
n = (int) strtonum(lines[idx], INT_MIN, INT_MAX, &errstr);
2021-12-10 20:41:36 +00:00
if (errstr) {
fprintf(stderr, "Failed to convert %s to int. Returning NULL\n", lines[idx]);
free(i);
del_lines(lines);
return NULL;
2021-12-10 20:41:36 +00:00
}
i[idx] = n;
}
del_lines(lines);
return i;
}
void del_split(char **sp) {
free(sp[0]);
free(sp);
}
void del_lines(char **lines) {
del_split(lines);
}