-
Notifications
You must be signed in to change notification settings - Fork 0
/
map_parser.c
101 lines (92 loc) · 2.64 KB
/
map_parser.c
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
96
97
98
99
100
101
/* ************************************************************************** */
/* */
/* :::::::: */
/* map_parser.c :+: :+: */
/* +:+ */
/* By: cschuijt <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/11/11 14:29:03 by cschuijt #+# #+# */
/* Updated: 2022/11/11 14:29:03 by cschuijt ######## odam.nl */
/* */
/* ************************************************************************** */
#include "so_long.h"
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
t_map *initialize_map(char *path)
{
int fd;
char *map_str;
char **map_rows;
t_map *map_struct;
validate_filename(path);
fd = open(path, O_RDONLY);
if (fd < 0)
exit_perror("error opening file");
map_str = read_map_from_file(fd);
close(fd);
if (!*map_str)
exit_message("map is empty");
validate_empty_lines(map_str);
map_rows = ft_split(map_str, '\n');
if (!map_rows)
exit_perror("malloc error in ft_split");
run_map_validations(map_rows, map_str);
map_struct = initialize_map_struct(map_rows);
free(map_str);
validate_map_solvability(map_struct);
validate_patrol_locations(map_struct);
fill_in_map_name(map_struct, path);
return (map_struct);
}
// Returns the entire map as a string, without newlines stripped.
char *read_map_from_file(int fd)
{
char *map;
char *map2;
char *line;
map = ft_calloc(1, 1);
if (!map)
exit_perror("malloc error");
while (1)
{
line = get_next_line(fd);
if (line)
{
map2 = ft_strjoin(map, line);
free(map);
free(line);
if (!map2)
exit_perror("malloc error");
map = map2;
}
else
break ;
}
return (map);
}
void run_map_validations(char **map_rows, char *map_str)
{
validate_map_measurements(map_rows);
validate_map_boundaries(map_rows);
validate_map_content(map_str);
}
// Exits unless the file ends in the .ber extension.
void validate_filename(char *file)
{
size_t len;
len = ft_strlen(file);
if (len < 5)
exit_message("invalid filename, needs to end in .ber");
if (ft_strncmp(".ber", file + len - 4, 5))
exit_message("invalid filename, needs to end in .ber");
}
void validate_empty_lines(char *map)
{
while (*map)
{
if (*map == '\n' && *(map + 1) == '\n')
exit_message("map contains empty lines");
map++;
}
}