ARMv8/src/fileio.c
2024-06-12 17:48:23 +01:00

98 lines
2.5 KiB
C

#include <string.h>
#include "global.h"
#include "fileio.h"
#define MAX_ASM_LINE_LENGTH 300
int isValidFileFormat(char filename[], char expectedExtension[]){
char *pointLoc = strrchr(filename, '.');
if(pointLoc != NULL){
if(strcmp(pointLoc, expectedExtension)==0){
return(1);
}
}
return(0);
}
void writeBinaryFile(word instrs[], char outputFile[], int numInstrs) {
FILE *fp = fopen(outputFile, "wb");
if (fp == NULL) {
fprintf(stderr, "Error: Could not open file %s\n", outputFile);
exit(EXIT_FAILURE);
}
fwrite(instrs, sizeof(word), numInstrs, fp);
fclose(fp);
}
int countLines(char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "Error: Could not read file %s\n", filename);
exit(EXIT_FAILURE);
}
int count = 0;
char c;
char prevC = '\n';
while ((c = fgetc(file)) != EOF) {
if (c == '\n' && prevC != '\n') {
count++;
}
prevC = c;
}
return count;
}
char **readAssemblyFile(char filename[], int lineCount) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Error: Could not read file %s\n", filename);
exit(EXIT_FAILURE);
}
char **lines = malloc(sizeof(char *) * lineCount + 1);
if (lines == NULL) {
fprintf(stderr, "Error: Could not allocate memory to store the assembly lines");
exit(EXIT_FAILURE);
}
rewind(fp); // Back to the beginning of the file.
char buffer[MAX_ASM_LINE_LENGTH];
int currentLine = 0;
while (fgets(buffer, MAX_ASM_LINE_LENGTH, fp) != NULL) {
if (buffer[strlen(buffer) - 1] != '\n') {
// It was actually longer than the maximum.
// NOTE: I believe this must mean that this is a malformed line, so throw an error.
fprintf(stderr, "Error: Line %d in the file %s is too long\n", currentLine, filename);
exit(EXIT_FAILURE);
}
if (*buffer == '\n') {
// Skip empty lines.
continue;
}
lines[currentLine] = malloc(strlen(buffer) + 1);
if (lines[currentLine] == NULL) {
fprintf(stderr, "Error: Could not allocate memory to store the assembly line");
exit(EXIT_FAILURE);
}
strcpy(lines[currentLine], buffer);
currentLine++;
}
if (ferror(fp)) {
fprintf(stderr, "Error: Could not read file %s", filename);
exit(EXIT_FAILURE);
}
return lines;
}