From e4bae38e3a5d345c025ed9edddbf401c81756dd5 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Mon, 13 Jul 2020 00:07:56 +0200 Subject: Finish 'downloaded' command --- fileutils.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'fileutils.c') diff --git a/fileutils.c b/fileutils.c index 233138c..137373b 100644 --- a/fileutils.c +++ b/fileutils.c @@ -1,6 +1,9 @@ #include "fileutils.h" +#include "alloc.h" +#include #include +#include #include #include @@ -12,3 +15,33 @@ const char* get_home_dir() { } return home_dir; } + +int file_get_content(const char *filepath, char **data, long *size) { + int result = 0; + FILE *file = fopen(filepath, "rb"); + if(!file) { + int err = -errno; + perror(filepath); + return err; + } + + fseek(file, 0, SEEK_END); + *size = ftell(file); + if(*size == -1) { + fprintf(stderr, "Failed to tell the size of file %s, is it not a file?\n", filepath); + result = -1; + goto cleanup; + } + fseek(file, 0, SEEK_SET); + + *data = alloc_or_crash(*size); + if((long)fread(*data, 1, *size, file) != *size) { + fprintf(stderr, "Failed to read all bytes in file %s\n", filepath); + result = -1; + goto cleanup; + } + + cleanup: + fclose(file); + return result; +} -- cgit v1.2.3