From 594c1922bccf1f15e8a7bb2a6e1303e865e2568d Mon Sep 17 00:00:00 2001 From: Evan Burkey Date: Wed, 3 May 2023 14:26:58 -0700 Subject: [PATCH] add get_binary --- docs.sh | 6 ++++++ docs/lfinput.md | 14 ++++++++++++++ src/lfinput.c | 35 +++++++++++++++++++++++++++++++++-- 3 files changed, 53 insertions(+), 2 deletions(-) create mode 100755 docs.sh diff --git a/docs.sh b/docs.sh new file mode 100755 index 0000000..eebe093 --- /dev/null +++ b/docs.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +mkdocs build +ssh debian@fputs.com rm -rf /var/www/fputs.com/docs/libflint +ssh debian@fputs.com mkdir -p /var/www/fputs.com/docs/libflint +scp -r site/* debian@fputs.com:/var/www/fputs.com/docs/libflint/ diff --git a/docs/lfinput.md b/docs/lfinput.md index 4247667..75d89f2 100644 --- a/docs/lfinput.md +++ b/docs/lfinput.md @@ -4,6 +4,20 @@ I/O module to assist with consuming data from files ## Functions +### 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. + +```c +char *get_binary(const char *path); + +/* Usage */ +char *buf = get_binary("/home/evan/binfile"); +free(buf); +``` + + ### get_input Reads a file at `path` and returns the contents as a single string. The string is allocated inside the function and diff --git a/src/lfinput.c b/src/lfinput.c index 71b47b3..edb8d0a 100644 --- a/src/lfinput.c +++ b/src/lfinput.c @@ -11,7 +11,7 @@ #include "lfinput.h" -char *get_input(const char *path) { +static FILE* open_file(const char *path, size_t *fsz) { FILE *fp = NULL; fp = fopen(path, "r"); if (fp == NULL) { @@ -20,9 +20,40 @@ char *get_input(const char *path) { } fseek(fp, 0, SEEK_END); - size_t fsz = ftell(fp); + *fsz = ftell(fp); rewind(fp); + return fp; +} + +char *get_binary(const char *path) { + size_t fsz = 0; + FILE *fp = open_file(path, &fsz); + if (fp == NULL) { + return NULL; + } + + char *buf = NULL; + buf = malloc(fsz); + if (buf == NULL) { + fprintf(stderr, "Failed to malloc buf. Returning NULL\n"); + fclose(fp); + return NULL; + } + + fread(buf, 1, fsz, fp); + fclose(fp); + + return buf; +} + +char *get_input(const char *path) { + size_t fsz = 0; + FILE *fp = open_file(path, &fsz); + if (fp == NULL) { + return NULL; + } + char *buf = NULL; buf = malloc(fsz + 1); if (buf == NULL) {