From d235876f94f84dca15520a20bb476b916b927afb Mon Sep 17 00:00:00 2001 From: hachem Date: Sun, 30 Aug 2026 01:31:15 +0200 Subject: add: read files into memory --- src/io/file.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/io/file.h | 13 +++++++++++++ src/main.c | 10 ++++++---- 3 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 src/io/file.c create mode 100644 src/io/file.h diff --git a/src/io/file.c b/src/io/file.c new file mode 100644 index 0000000..8ce8eef --- /dev/null +++ b/src/io/file.c @@ -0,0 +1,61 @@ +#include +#include + +#include "io/file.h" + +bool read_file(const char* path, struct File* out) +{ + FILE* stream = fopen(path, "rb"); + if (stream == NULL) + { + fprintf(stderr, "error: could not open '%s'\n", path); + return false; + } + + if (fseek(stream, 0, SEEK_END) != 0) + { + fprintf(stderr, "error: could not read '%s'\n", path); + fclose(stream); + return false; + } + + long length = ftell(stream); + if (length < 0) + { + fprintf(stderr, "error: could not read '%s'\n", path); + fclose(stream); + return false; + } + rewind(stream); + + size_t size = (size_t)length; + char* data = malloc(size + 1); + if (data == NULL) + { + fprintf(stderr, "error: out of memory reading '%s'\n", path); + fclose(stream); + return false; + } + + if (fread(data, 1, size, stream) != size) + { + fprintf(stderr, "error: could not read '%s'\n", path); + free(data); + fclose(stream); + return false; + } + + data[size] = '\0'; + fclose(stream); + + out->data = data; + out->size = size; + return true; +} + +void free_file(struct File* file) +{ + free(file->data); + file->data = NULL; + file->size = 0; +} diff --git a/src/io/file.h b/src/io/file.h new file mode 100644 index 0000000..7d15bd0 --- /dev/null +++ b/src/io/file.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include + +struct File +{ + char* data; + size_t size; +}; + +bool read_file(const char* path, struct File* out); +void free_file(struct File* file); diff --git a/src/main.c b/src/main.c index a14d2ba..1d97acb 100644 --- a/src/main.c +++ b/src/main.c @@ -1,5 +1,6 @@ #include +#include "io/file.h" #include "cli/args.h" int main(int argc, char** argv) @@ -12,11 +13,12 @@ int main(int argc, char** argv) if (result == PARSE_ERROR) return 1; - static const char* target_names[] = { "nasm", "fasm", "masm" }; + struct File source; + if (!read_file(args.input_path, &source)) + return 1; - printf("input: %s\n", args.input_path); - printf("output: %s\n", args.output_path != NULL ? args.output_path : ""); - printf("target: %s\n", target_names[args.target]); + printf("read %zu bytes from %s\n", source.size, args.input_path); + free_file(&source); return 0; } -- cgit v1.3