From de40227d08f47946904a074a9408d35a8a3cbd1b Mon Sep 17 00:00:00 2001 From: Themis Demetriades Date: Thu, 30 May 2024 14:17:43 +0100 Subject: [PATCH] Add binary file loading w/ S --- src/fileio.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/fileio.h | 9 +++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/fileio.c create mode 100644 src/fileio.h diff --git a/src/fileio.c b/src/fileio.c new file mode 100644 index 0000000..b8c0574 --- /dev/null +++ b/src/fileio.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include "fileio.h" + +/* Loads a binary file located at filePath to memory, taking up a block of exactly memorySize bytes, + and returns the starting address of the data. If memorySize is insufficient to store the entire file, + an appropriate error is reported. Excess memory is set to 0 bit values. */ + +word *fileio_loadBin(const char *filePath, size_t memorySize) { + FILE *file = fopen(filePath, "rb"); + if (file == NULL) { + fprintf(stderr, "Couldn't open %s!\n", filePath); + exit(EXIT_FAILURE); + } + + word *fileData = malloc(memorySize); + if (fileData == NULL) { + fprintf(stderr, "Ran out of memory attempting to load %s!\n", filePath); + exit(EXIT_FAILURE); + } + + // Loop while reading from the file yields data. Only terminates if EOF is reached or ERROR occurs. + // Explicitly deal with attempting to write too much data to memory block, rather than allow segfault. + const size_t wordCount = memorySize/sizeof(word); + int i = 0; + while (fread(fileData + i, sizeof(word), 1, file)) { + if (i >= wordCount) { + fprintf(stderr, "Attempting to load binary %s to memory of smaller size %zu!\n", filePath, memorySize); + exit(EXIT_FAILURE); + } + + i++; + } + + if (ferror(file)) { + fprintf(stderr, "Encountered error attempting to read %s!\n", filePath); + exit(EXIT_FAILURE); + } + assert(fclose(file) != EOF); + + // If part of memory block was left uninitialized, initialize it to zero. + if (i < wordCount) { + memset(fileData + i, 0, (wordCount - i) * sizeof(word)); + } + return fileData; +} diff --git a/src/fileio.h b/src/fileio.h new file mode 100644 index 0000000..8a439bf --- /dev/null +++ b/src/fileio.h @@ -0,0 +1,9 @@ +#ifndef __FILEIO__ +#define __FILEIO__ +#include +#include "global.h" + +#define EXIT_FAILURE 1 + +extern word *fileio_loadBin(const char *filePath, size_t memorySize); +#endif