69 lines
1.4 KiB
C
69 lines
1.4 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"
|
|
|
|
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);
|
|
}
|
|
|
|
return file;
|
|
}
|
|
|
|
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;
|
|
}
|