aoc-2023/libs/fileLoader.c

52 lines
986 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 *load_file_to_mem(char *filename)
{
struct OpenFile *file = NULL;
file = (struct OpenFile *)
malloc(sizeof(struct OpenFile));
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(statbuf.st_size);
memcpy(file->fileData, filecontents, statbuf.st_size);
if (err != 0)
{
printf("Unmapping failed");
exit(1);
}
close(fd);
return file;
}