diff options
author | zlago | 2024-09-25 14:02:49 +0200 |
---|---|---|
committer | zlago | 2024-09-25 14:19:32 +0200 |
commit | 9942429dbb83fed5532c070f8afe41d6ddcd66d2 (patch) | |
tree | 70f7d3872de143a7f256b3913e2bf52724d23c3a /utl/json2map/common.c | |
parent | b23a3ab831f91553d34a48f51370ed9525de07ac (diff) |
parallax
Diffstat (limited to 'utl/json2map/common.c')
-rw-r--r-- | utl/json2map/common.c | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/utl/json2map/common.c b/utl/json2map/common.c new file mode 100644 index 0000000..c401fc1 --- /dev/null +++ b/utl/json2map/common.c @@ -0,0 +1,44 @@ +#include <stdio.h> +#include <stdlib.h> +#include "common.h" + +struct blob load_file(char const *const name) { + const size_t START_SIZE = 8192; + FILE *file = fopen(name, "rb"); + if (file == NULL) { + return (struct blob) {.data = NULL}; + } + char *data = malloc(START_SIZE); + size_t allocated = START_SIZE; + size_t used = 0; + while (1) { + size_t read = fread(data + used, 1, allocated - used, file); + if (read != allocated - used) { + used += read; + break; + } + used += read; + allocated *= 2; + void *const newdata = realloc(data, allocated); + if (newdata == NULL) { + goto realloc_error; + } + data = newdata; + } + if (used == 0) { + free(data); + fclose(file); + return (struct blob) {.data = NULL, .size = 0}; + } + void *const newdata = realloc(data, used); + if (newdata == NULL) { + goto realloc_error; + } + fclose(file); + return (struct blob) {.data = newdata, .size = used}; + + realloc_error: + free(data); + fclose(file); + return (struct blob) {.data = NULL}; +} |