From affb5ee5b9fac8a88daa766960602802e35484b8 Mon Sep 17 00:00:00 2001 From: Charlie Stanton Date: Fri, 1 Oct 2021 21:02:48 +0100 Subject: Add reading from a file --- cudl.c | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/cudl.c b/cudl.c index 94e3f7f..9c71d57 100644 --- a/cudl.c +++ b/cudl.c @@ -30,6 +30,24 @@ struct cudl_value { #define CUDL_OK 0 #define CUDL_ERR_OUT_OF_MEMORY 1 #define CUDL_ERR_MISSING_VALUE 2 +#define CUDL_ERR_READING 3 + +static char *fread_all(FILE *file) { + size_t size; + char *buffer; + fseek(file, 0, SEEK_END); + size = ftell(file); + rewind(file); + clearerr(file); + if ((buffer = malloc(size + 1)) == NULL) + return NULL; + if (fread(buffer, 1, size, file) != size) { + free(buffer); + return NULL; + } + buffer[size] = '\0'; + return buffer; +} void cudl_debug(struct cudl_value *value) { } @@ -50,7 +68,15 @@ void cudl_deinit_value(struct cudl_value value) { } } -int cudl_parse_from_file(FILE input_file, struct cudl_value *value) { +int cudl_parse_from_file(FILE *file, struct cudl_value *value) { + char *input; + if ((input = fread_all(file)) == NULL) { + if (ferror(file)) + return CUDL_ERR_READING; + else + return CUDL_ERR_OUT_OF_MEMORY; + } + return cudl_parse(input, value); } int cudl_parse(char *input, struct cudl_value *value) { -- cgit v1.2.3