aoc-2023/libs/fileLoader.c

55 lines
1.1 KiB
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"
char *load_file_to_mem(char *filename) {
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);
}
return filecontents;
}
int unmap_file(char *ptr, char *filename) {
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);
err = munmap(ptr, statbuf.st_size);
if (err != 0)
{
printf("Unmapping failed");
return 1;
}
return 0;
}