From 2c44fa54fb88b658b1ca96028a1e4cbbf3429871 Mon Sep 17 00:00:00 2001 From: Raquezin Date: Sun, 16 Nov 2025 22:59:05 +0100 Subject: [PATCH] save and load matrix functions --- include/errores.h | 3 ++- include/matrix.h | 21 +++++++++++++++++++++ src/matrix.c | 30 ++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/include/errores.h b/include/errores.h index 6d88336..ad2a19f 100644 --- a/include/errores.h +++ b/include/errores.h @@ -8,7 +8,8 @@ typedef enum { ERR_INF_SOL, ERR_NO_SOL, ERR_NOT_INVERTIBLE, - ERR_DIV_BY_ZERO + ERR_DIV_BY_ZERO, + ERR_FILE_NOT_FOUND } ErrorCode; #endif // ERRORES_H \ No newline at end of file diff --git a/include/matrix.h b/include/matrix.h index 1aca80b..412b823 100644 --- a/include/matrix.h +++ b/include/matrix.h @@ -1,6 +1,8 @@ #ifndef MATRIX_H #define MATRIX_H +#include "errores.h" + #define REGISTRY_CAPACITY 100 /** @@ -46,4 +48,23 @@ Matrix create_matrix(const int rows, const int cols, const float val); */ void free_registry(); +/** + * @brief Save a matrix to a binary file. + * + * @param a The matrix to save. + * @param filename Name of the file. + * @return Error code indicating the result of the operation. + */ +ErrorCode save_matrix(const Matrix a, const char *filename); + +/** + * @brief Load a matrix from a binary file. + * + * @param filename Name of the file. + * @param err Pointer to store the error code. + * @return The loaded matrix, or a default matrix in case of error. + */ +Matrix load_matrix(const char *filename, ErrorCode *err); + + #endif // MATRIX_H \ No newline at end of file diff --git a/src/matrix.c b/src/matrix.c index 3d4d34e..e7df269 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -2,6 +2,7 @@ #include #include "matrix.h" #include "operations_utils.h" +#include "errores.h" static MatrixRegistry registry = {.index = 0}; static Matrix default_matrix = {.row = 0, .col = 0, .data = NULL}; @@ -34,3 +35,32 @@ void free_registry() { free(registry.data[i]); } } + +ErrorCode save_matrix(const Matrix a, const char* filename) { + FILE* f = fopen(filename, "wb"); + if (!f) return ERR_FILE_NOT_FOUND; + + fwrite(&a.row, sizeof(int), 1, f); + fwrite(&a.col, sizeof(int), 1, f); + fwrite(a.data, sizeof(float), a.row * a.col, f); + + fclose(f); + return ERR_NONE; +} + +Matrix load_matrix(const char* filename, ErrorCode* err) { + FILE* f = fopen(filename, "rb"); + if (!f) { + *err = ERR_NONE; + return default_matrix; + } + + int rows, cols; + fread(&rows, sizeof(int), 1, f); + fread(&cols, sizeof(int), 1, f); + Matrix m = create_matrix(rows, cols, 0.0f); + fread(m.data, sizeof(float), rows * cols, f); + fclose(f); + *err = ERR_NONE; + return m; +}