42_cube3D/map/parsing.c

90 lines
1.6 KiB
C

#include "./parsing_private.h"
#include "map.h"
#include <stddef.h>
static ssize_t get_nb_line(const char *path)
{
int fd;
char readed[1];
size_t i;
fd = open(path, O_RDONLY);
if (fd == -1)
return (-1);
i = 1;
while (read(fd, readed, 1))
{
if (readed[0] == '\n')
i++;
}
close(fd);
return (i);
}
static char **read_map(const char *path)
{
int fd;
size_t i;
char **map;
map = malloc(sizeof(char *) * (get_nb_line(path) + 1));
if (map == NULL)
return (NULL);
fd = open(path, O_RDONLY);
if (fd == -1)
{
free(map);
return (NULL);
}
i = 0;
map[i] = get_next_line(fd);
while (map[i] != NULL)
{
map[i][ft_strlen(map[i]) - 1] = '\0';
i++;
map[i] = get_next_line(fd);
}
return (map);
}
t_map *map_parsing(const char *path)
{
char **file_content;
char ***header;
char **body;
size_t header_size;
t_map *map;
if (parsing_meta(path))
return (NULL);
map = malloc(sizeof(t_map));
if (map == NULL)
return (NULL);
file_content = read_map(path);
if (file_content == NULL)
{
ft_eprintf("map: file error");
return (NULL);
}
header = get_header((const char **) file_content, &header_size);
if (header_is_valid(header, map) == 0)
{
ft_freer_tab_ultimate(1, file_content);
ft_freer_ultimate(1, map);
return (NULL);
}
//ici aussi header;
body = get_body((const char **) file_content, header_size);
ft_freer_tab_ultimate(1, file_content);
if (body_is_valid((const char **) body, map) == 0)
{
ft_freer_ultimate(1, map);
// faudra free
return (NULL);
}
map->map = body;
map->direction = map->map[map->spawn_y][map->spawn_x];
map->map[map->spawn_y][map->spawn_x] = '0';
return (map);
}