fix incorrect fileio.c

This commit is contained in:
EDiasAlberto 2024-06-11 20:23:00 +01:00
parent 6153db7737
commit 173bdf08ec

View File

@ -1,48 +1,56 @@
#include <assert.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "fileio.h"
#include "global.h"
/* Loads a binary file located at filePath to memory, taking up a block of exactly memorySize bytes, #define MAX_ASM_LINE_LENGTH 100
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. */
byte *fileio_loadBin(const char *filePath, size_t memorySize) { int isValidFileFormat(char filename[], char expectedExtension[]){
FILE *file = fopen(filePath, "rb"); int *pointLoc = strrchr(filename, '.');
if (file == NULL) {
fprintf(stderr, "Couldn't open %s!\n", filePath); if(pointLoc != NULL){
exit(EXIT_FAILURE); if(strcmp(pointLoc, expectedExtension)==0){
return(1);
}
}
return(0);
} }
byte *fileData = malloc(memorySize); int writeBinaryFile(word instrs[], char outputFile[]){
if (fileData == NULL) {
fprintf(stderr, "Ran out of memory attempting to load %s!\n", filePath); if (!isValidFileFormat(filename, "bin")){
exit(EXIT_FAILURE); return(-1);
} }
// Loop while reading from the file yields data. Only terminates if EOF is reached or ERROR occurs. FILE *fp;
// Explicitly deal with attempting to write too much data to memory block, rather than allow segfault.
const size_t byteCount = memorySize/sizeof(byte); fp = fopen(outputFile, "wb");
int i = 0;
while (fread(fileData + i, sizeof(byte), 1, file)) { if(fp == NULL){
if (i >= byteCount) { return(-1);
fprintf(stderr, "Attempting to load binary %s to memory of smaller size %zu!\n", filePath, memorySize);
exit(EXIT_FAILURE);
} }
i++; fwrite(instrs, 4, sizeof(instrs), fp);
fclose(fp);
return(0);
} }
if (ferror(file)) { int readAssemblyFile(char inputFile[]) {
fprintf(stderr, "Encountered error attempting to read %s!\n", filePath); if (!isValidFileFormat(filename, "s")){
exit(EXIT_FAILURE); return(1);
} }
assert(fclose(file) != EOF);
// If part of memory block was left uninitialized, initialize it to zero. FILE *fp;
if (i < byteCount) { char savedLine[MAX_ASM_LINE_LENGTH];
memset(fileData + i, 0, (byteCount - i) * sizeof(byte));
fp = fopen(inputFile, "r");
if(fp == NULL){
return(-1);
} }
return fileData;
while (fgets(savedLine, MAX_ASM_LINE_LENGTH-1, fp) != NULL) {
//pass line to parser
}
return(0);
} }