aboutsummaryrefslogtreecommitdiff
path: root/src/file.c
blob: 511b580419c9885d43a0b3e1939c65c48a93a22d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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;
}