switched file io to c standard

This commit is contained in:
Nicolas 2025-10-04 23:06:45 +02:00
parent dcb888d514
commit 5d3702a1b2
1 changed files with 22 additions and 21 deletions

View File

@ -1,9 +1,5 @@
#include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include "runmem.h" #include "runmem.h"
#include "mem_man.h" #include "mem_man.h"
@ -13,36 +9,41 @@ int main(int argc, char *argv[]) {
return EXIT_FAILURE; return EXIT_FAILURE;
} }
// Open the file FILE *f = fopen(argv[1], "rb");
int fd = open(argv[1], O_RDONLY); if (!f) {
if (fd < 0) { perror("fopen");
perror("open");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
// Get file size /* Determine file size */
struct stat st; if (fseek(f, 0, SEEK_END) != 0) {
if (fstat(fd, &st) < 0) { perror("fseek");
perror("fstat"); fclose(f);
close(fd);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
long sz = ftell(f);
if (sz < 0) {
perror("ftell");
fclose(f);
return EXIT_FAILURE;
}
rewind(f);
if (st.st_size == 0) { if (sz == 0) {
fprintf(stderr, "Error: File is empty\n"); fprintf(stderr, "Error: File is empty\n");
close(fd); fclose(f);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
uint8_t *file_buff = allocate_buffer_memory((uint32_t)st.st_size); uint8_t *file_buff = allocate_buffer_memory((uint32_t)sz);
// Read file into allocated memory /* Read file into allocated memory */
if (read(fd, file_buff, (long unsigned int)st.st_size) != st.st_size) { size_t nread = fread(file_buff, 1, (size_t)sz, f);
perror("read"); fclose(f);
close(fd); if (nread != (size_t)sz) {
perror("fread");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
close(fd);
parse_commands(file_buff); parse_commands(file_buff);