aboutsummaryrefslogtreecommitdiff
path: root/src/file.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/file.c')
-rw-r--r--src/file.c95
1 files changed, 95 insertions, 0 deletions
diff --git a/src/file.c b/src/file.c
new file mode 100644
index 0000000..511b580
--- /dev/null
+++ b/src/file.c
@@ -0,0 +1,95 @@
+#include "file.h"
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include "utilities.h"
+
+struct data
+{
+ int x;
+ int y;
+ int value;
+};
+
+static int **list_to_map(struct data *values, int count, int width, int height)
+{
+ int **map = malloc(sizeof_2d(width, height, sizeof(int)));
+ init2d((void **)map, width, height, sizeof(int));
+ for (int i = 0; i < count; i++)
+ map[values[i].x][values[i].y] = values[i].value;
+ return map;
+}
+
+static void get_numbers(char *line, int *left_int, int *right_int)
+{
+ char *left, *right;
+ if (find_lr_ints(line, &left, &right))
+ {
+ *left_int = strtol(left, NULL, 10);
+ *right_int = strtol(right, NULL, 10);
+ }
+}
+
+struct maze *maze_from_file(char *path)
+{
+ FILE *file = fopen(path, "r");
+ if (file == NULL)
+ return NULL;
+ struct maze *maze = malloc(sizeof(struct maze));
+ struct data values[50 * 50];
+ char buffer[256];
+ int i = 0, y = 0, max_width = 0;
+ while (fgets(buffer, 256, file))
+ {
+ int length = strlen(buffer);
+ if (length > 0)
+ {
+ if (length > 5 && !strncmp(buffer, "start", 5))
+ {
+ get_numbers(buffer + 5, &(maze->starting_point.x), &(maze->starting_point.y));
+ }
+ else if (length > 3 && !strncmp(buffer, "end", 3))
+ {
+ get_numbers(buffer + 3, &(maze->end_point.x), &(maze->end_point.y));
+ }
+ else
+ {
+ int x;
+ for (x = 0; buffer[x] != 10; x++)
+ {
+ values[i].x = x;
+ values[i].y = y;
+ values[i].value = buffer[x] == '0' ? 0 : 1;
+ i++;
+ }
+ if (x > max_width)
+ max_width = x;
+ y++;
+ }
+ }
+ }
+ fclose(file);
+ maze->width = max_width;
+ maze->height = y;
+ maze->map = list_to_map(values, i, maze->width, maze->height);
+ return maze;
+}
+
+int maze_to_file(char *path, struct maze *maze)
+{
+ FILE *file = fopen(path, "w");
+ if (file == NULL)
+ return -1;
+ fprintf(file, "start=(%d,%d)\n", maze->starting_point.x, maze->starting_point.y);
+ fprintf(file, "end=(%d,%d)\n", maze->end_point.x, maze->end_point.y);
+ for (int y = 0; y < maze->height; y++)
+ {
+ for (int x = 0; x < maze->width; x++)
+ {
+ fprintf(file, "%d", maze->map[x][y]);
+ }
+ fprintf(file, "\n");
+ }
+ fclose(file);
+ return 0;
+} \ No newline at end of file