From 173bdf08ec6a6e59d0e63f18c29fb3799f1c3831 Mon Sep 17 00:00:00 2001 From: EDiasAlberto Date: Tue, 11 Jun 2024 20:23:00 +0100 Subject: [PATCH] fix incorrect fileio.c --- src/fileio.c | 88 ++++++++++++++++++++++++++++------------------------ 1 file changed, 48 insertions(+), 40 deletions(-) diff --git a/src/fileio.c b/src/fileio.c index 1dcdd77..96e5cd3 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -1,48 +1,56 @@ -#include #include #include -#include "fileio.h" -#include "global.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. */ +#define MAX_ASM_LINE_LENGTH 100 -byte *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); - } +int isValidFileFormat(char filename[], char expectedExtension[]){ + int *pointLoc = strrchr(filename, '.'); - byte *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 byteCount = memorySize/sizeof(byte); - int i = 0; - while (fread(fileData + i, sizeof(byte), 1, file)) { - if (i >= byteCount) { - fprintf(stderr, "Attempting to load binary %s to memory of smaller size %zu!\n", filePath, memorySize); - exit(EXIT_FAILURE); + if(pointLoc != NULL){ + if(strcmp(pointLoc, expectedExtension)==0){ + return(1); } - - 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 < byteCount) { - memset(fileData + i, 0, (byteCount - i) * sizeof(byte)); - } - return fileData; + return(0); +} + +int writeBinaryFile(word instrs[], char outputFile[]){ + + if (!isValidFileFormat(filename, "bin")){ + return(-1); + } + + FILE *fp; + + fp = fopen(outputFile, "wb"); + + if(fp == NULL){ + return(-1); + } + + fwrite(instrs, 4, sizeof(instrs), fp); + fclose(fp); + + return(0); +} + +int readAssemblyFile(char inputFile[]) { + if (!isValidFileFormat(filename, "s")){ + return(1); + } + + FILE *fp; + char savedLine[MAX_ASM_LINE_LENGTH]; + + fp = fopen(inputFile, "r"); + + if(fp == NULL){ + return(-1); + } + + while (fgets(savedLine, MAX_ASM_LINE_LENGTH-1, fp) != NULL) { + //pass line to parser + } + + return(0); }