diff options
author | Aryadev Chavali <aryadev@aryadevchavali.com> | 2023-08-25 20:03:23 +0100 |
---|---|---|
committer | Aryadev Chavali <aryadev@aryadevchavali.com> | 2023-08-25 20:03:23 +0100 |
commit | 21c03264e65042db3b5856fba8a6cd1099438f96 (patch) | |
tree | da4208818b6703ffcff557574b030be6fb42984e /file-handler.c | |
parent | 58970e8a68583e61e93091989af335cdac218085 (diff) | |
download | abelian-sandpile-21c03264e65042db3b5856fba8a6cd1099438f96.tar.gz abelian-sandpile-21c03264e65042db3b5856fba8a6cd1099438f96.tar.bz2 abelian-sandpile-21c03264e65042db3b5856fba8a6cd1099438f96.zip |
(main|file-handler)~fixed some stuff
Big bug with file handler: I can write data well, but reading it
causes some trace error which I cannot be bothered to fix. So I'll
just work on making the step function way more efficient.
Diffstat (limited to 'file-handler.c')
-rw-r--r-- | file-handler.c | 43 |
1 files changed, 38 insertions, 5 deletions
diff --git a/file-handler.c b/file-handler.c index 0f9e838..760595c 100644 --- a/file-handler.c +++ b/file-handler.c @@ -36,27 +36,60 @@ void buffer_tighten(buffer_t *buffer) buffer->available = buffer->used; } +#define IS_DIGIT(c) (c <= '9' && c >= '0') + bool load_from_file(state_t *state, const char *filepath) { - memset(state->data, 0, state->dwidth * state->dwidth); // Read file completely FILE *fp = fopen(filepath, "r"); + if (!fp) + return false; + buffer_t buffer; buffer_init(&buffer); + size_t acc = 0; size_t bytes_read = 0; - while ((bytes_read = - fread(buffer.data, sizeof(*buffer.data), CHUNK_SIZE, fp)) != 0) + while ((bytes_read = fread(buffer.data + acc, sizeof(*buffer.data), + CHUNK_SIZE, fp)) != 0) { buffer.used += bytes_read; + acc += bytes_read; buffer_realloc(&buffer, buffer.available + CHUNK_SIZE); } fclose(fp); buffer_tighten(&buffer); - // Now parse it + // first line is width + state->dwidth = atoi(buffer.data); + state->data = calloc(state->dwidth * state->dwidth, sizeof(*state->data)); + state->multiplier = state->window_len / state->dwidth; - free(buffer.data); + size_t line_size = strcspn(buffer.data, "\n"); + char *ptr = buffer.data + line_size + 1; + size_t i = 0; + for (ptr = strpbrk(ptr, "\n"); ptr && i < state->dwidth; + ptr = strpbrk(ptr, "\n"), ++i) + { + if (ptr[1] == '\0') + break; + ++ptr; + size_t j = 0; + size_t line_size = strcspn(ptr, "\n"); + for (size_t lptr = 0; lptr < line_size;) + { + size_t end_of_digit = lptr; + for (; IS_DIGIT(ptr[end_of_digit]); ++end_of_digit) + continue; + state->data[(i * state->dwidth) + j] = atoi(ptr + lptr); + + lptr = end_of_digit + 1; + ++j; + } + ++ptr; + } + + free(buffer.data); return true; } |