utils.c (1310B)
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
file_t
read_file(const char *filename) {
long fsize;
char *source;
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
fprintf(stderr, "file not found\n");
fclose(fp);
return (file_t){.contents = NULL, .len = 0};
}
if (fseek(fp, 0, SEEK_END) != 0) {
fprintf(stderr, "could not read file\n");
fclose(fp);
exit(1);
}
fsize = ftell(fp);
if (fsize < 0) {
fprintf(stderr, "could not read size of file to load\n");
fclose(fp);
exit(1);
}
fseek(fp, 0, SEEK_SET);
source = malloc(fsize + 1);
if (!source) {
fprintf(stderr, "could not allocate memory to read file\n");
exit(1);
}
fread(source, fsize, 1, fp);
fclose(fp);
source[fsize] = '\0';
return (file_t){.contents = source, .len = fsize};
}
void
separate_file_from_path(const char *fullpath, char **out_path, char **out_filename) {
char *path = strdup(fullpath);
char *filename = strrchr(path, '/');
if (filename == NULL) {
printf("No path found\n");
exit(1);
}
*filename = '\0';
filename++;
*out_path = strdup(path);
*out_filename = strdup(filename);
free(path);
}