summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2023-08-25 19:08:32 +0100
committerAryadev Chavali <aryadev@aryadevchavali.com>2023-08-25 19:08:32 +0100
commitf155f0e0884b18a9fdac3a302bb9c9fa1dd7e5aa (patch)
treefbaad842756f777ad4b37f667e4f49b7a3adf175
parent64f8df2592c2bf7cbedd2721ffeec39f74269041 (diff)
downloadabelian-sandpile-f155f0e0884b18a9fdac3a302bb9c9fa1dd7e5aa.tar.gz
abelian-sandpile-f155f0e0884b18a9fdac3a302bb9c9fa1dd7e5aa.tar.bz2
abelian-sandpile-f155f0e0884b18a9fdac3a302bb9c9fa1dd7e5aa.zip
(file-handler)+impl file for file handling
In particular I've implemented a standardised complete FILE * reader without relying on fseek (which may not work for pipes).
-rw-r--r--Makefile2
-rw-r--r--file-handler.c64
2 files changed, 65 insertions, 1 deletions
diff --git a/Makefile b/Makefile
index 5f13bd7..deb3b80 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
CC=gcc
CFLAGS=-Wall -Wextra -pedantic -ggdb -fsanitize=address
LIBS=-lm -lraylib
-OBJECTS=main.o
+OBJECTS=file-handler.o main.o
OUT=sandpile.out
ARGS=
diff --git a/file-handler.c b/file-handler.c
new file mode 100644
index 0000000..765eec5
--- /dev/null
+++ b/file-handler.c
@@ -0,0 +1,64 @@
+/* file-handler.c
+ * Created: 2023-08-25
+ * Author: Aryadev Chavali
+ * Description: Implementations of writing and loading state from files
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "./lib.h"
+
+#define CHUNK_SIZE 1024
+
+typedef struct Buffer
+{
+ char *data;
+ size_t used, available;
+} buffer_t;
+
+void buffer_init(buffer_t *buffer)
+{
+ *buffer =
+ (buffer_t){calloc(CHUNK_SIZE, sizeof(*buffer->data)), 0, CHUNK_SIZE};
+}
+
+void buffer_realloc(buffer_t *buffer, size_t new_size)
+{
+ buffer->data = realloc(buffer->data, new_size);
+ buffer->available = new_size;
+}
+
+void buffer_tighten(buffer_t *buffer)
+{
+ buffer->data = realloc(buffer->data, buffer->used + 1);
+ buffer->data[buffer->used] = '\0';
+ buffer->available = buffer->used;
+}
+
+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");
+ buffer_t buffer;
+ buffer_init(&buffer);
+ size_t bytes_read = 0;
+ while ((bytes_read =
+ fread(buffer.data, sizeof(*buffer.data), CHUNK_SIZE, fp)) != 0)
+ {
+ buffer.used += bytes_read;
+ buffer_realloc(&buffer, buffer.available + CHUNK_SIZE);
+ }
+ fclose(fp);
+ buffer_tighten(&buffer);
+
+ // Now parse it
+
+ free(buffer.data);
+
+ return true;
+}
+
+bool write_to_file(state_t *state, const char *filepath)
+{}