summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--file-handler.c43
-rw-r--r--main.c7
2 files changed, 43 insertions, 7 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;
}
diff --git a/main.c b/main.c
index a4a36b0..0a8e97a 100644
--- a/main.c
+++ b/main.c
@@ -116,9 +116,12 @@ int main(void)
}
if (state.thread_alive)
- pthread_cancel(step_thread);
+ {
+ state.thread_alive = false;
+ pthread_join(step_thread, NULL);
+ }
- write_to_file(&state, "data.out");
CloseWindow();
+ free(state.data);
return 0;
}