aoc-2023/libs/fileLoader.c
2023-12-05 11:49:28 +11:00

52 lines
982 B
C

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "fileLoader.h"
struct OpenFile
{
char *fileData;
int fileSize;
};
struct OpenFile load_file_to_mem(char *filename) {
struct OpenFile file;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
printf("\n\"%s \" could not open", filename);
exit(1);
}
struct stat statbuf;
int err = fstat(fd, &statbuf);
if (err < 0) {
printf("\n\"%s \" could not open", filename);
exit(2);
}
char *filecontents = mmap(NULL, statbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (filecontents == MAP_FAILED) {
printf("Mapping failed");
exit(3);
}
file.fileSize = statbuf.st_size;
file.fileData = malloc(file.fileSize);
memcpy(file.fileData, filecontents, file.fileSize);
if (err != 0) {
printf("Unmapping failed");
exit(1);
}
close(fd);
return file;
}