(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.
This commit is contained in:
2023-08-25 20:03:23 +01:00
parent 58970e8a68
commit 21c03264e6
2 changed files with 43 additions and 7 deletions

View File

@@ -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;
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;
}

7
main.c
View File

@@ -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;
}