-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_map.c
More file actions
84 lines (75 loc) · 2.03 KB
/
read_map.c
File metadata and controls
84 lines (75 loc) · 2.03 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* read_map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aylaaouf <aylaaouf@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/11 07:57:06 by aylaaouf #+# #+# */
/* Updated: 2025/03/20 02:58:23 by aylaaouf ### ########.fr */
/* */
/* ************************************************************************** */
#include "so_long.h"
void free_map_2(char **map)
{
int i;
if (!map)
return ;
i = 0;
while (map[i])
free(map[i++]);
free(map);
}
static void clean_line(char *line)
{
int len;
if (!line)
return ;
len = ft_strlen(line);
if (len > 0 && line[len - 1] == '\n')
line[len - 1] = '\0';
}
static char **fill_map(char ***map, int fd)
{
char *line;
int size;
size = 0;
line = get_next_line(fd);
while (line)
{
clean_line(line);
*map = realloc(*map, (size + 1) * sizeof(char *));
if (!(*map))
return (free(*map), free_map_2(*map), NULL);
(*map)[size++] = line;
line = get_next_line(fd);
}
*map = realloc(*map, (size + 1) * sizeof(char *));
if (!(*map))
return (free_map_2(*map), NULL);
(*map)[size] = NULL;
return (*map);
}
t_map *read_map(char *filename)
{
int fd;
t_map *map_data;
char **map;
map = NULL;
fd = open(filename, O_RDONLY);
if (fd < 0)
return (NULL);
map_data = malloc(sizeof(t_map));
ft_memset(map_data, 0, sizeof(t_map));
if (!map_data)
return (close(fd), NULL);
map_data->map = fill_map(&map, fd);
get_next_line(-1);
close(fd);
if (!map_data->map)
{
free(map_data);
return (NULL);
}
return (map_data);
}