From 86f3d5c9b97ddfc27dfc91fed02a468b66029292 Mon Sep 17 00:00:00 2001 From: Evan Burkey Date: Wed, 3 May 2023 14:46:38 -0700 Subject: [PATCH] fix get_binary --- docs/lfinput.md | 9 +++++---- include/lfinput.h | 2 +- src/lfinput.c | 9 ++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/lfinput.md b/docs/lfinput.md index 75d89f2..c8d350a 100644 --- a/docs/lfinput.md +++ b/docs/lfinput.md @@ -6,14 +6,15 @@ I/O module to assist with consuming data from files ### get_binary -Reads a file at `path` and returns the contents as a char* buffer. The buffer is allocated inside the function and -the user is responsible for freeing it when finished. +Reads a file at `path` and returns the contents as a char* buffer. The `fsz` parameter stores the length of the +returned array. The buffer is allocated inside the function, so the user is responsible for freeing it when finished. ```c -char *get_binary(const char *path); +char *get_binary(const char *path, size_t *fsz); /* Usage */ -char *buf = get_binary("/home/evan/binfile"); +size_t fsz = 0; +char *buf = get_binary("/home/evan/binfile", &fsz); free(buf); ``` diff --git a/include/lfinput.h b/include/lfinput.h index 192c305..2d6f3df 100644 --- a/include/lfinput.h +++ b/include/lfinput.h @@ -3,7 +3,7 @@ #include -char *get_binary(const char *); +char *get_binary(const char *, size_t *fsz); char *get_input(const char *); diff --git a/src/lfinput.c b/src/lfinput.c index edb8d0a..0c07f52 100644 --- a/src/lfinput.c +++ b/src/lfinput.c @@ -26,22 +26,21 @@ static FILE* open_file(const char *path, size_t *fsz) { return fp; } -char *get_binary(const char *path) { - size_t fsz = 0; - FILE *fp = open_file(path, &fsz); +char *get_binary(const char *path, size_t *fsz) { + FILE *fp = open_file(path, fsz); if (fp == NULL) { return NULL; } char *buf = NULL; - buf = malloc(fsz); + buf = malloc(*fsz); if (buf == NULL) { fprintf(stderr, "Failed to malloc buf. Returning NULL\n"); fclose(fp); return NULL; } - fread(buf, 1, fsz, fp); + fread(buf, 1, *fsz, fp); fclose(fp); return buf;