summaryrefslogtreecommitdiff
path: root/file-handler.c
diff options
context:
space:
mode:
Diffstat (limited to 'file-handler.c')
-rw-r--r--file-handler.c43
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;
}