/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   read_map_file.c                                    :+:    :+:            */
/*                                                     +:+                    */
/*   By: whaffman <whaffman@student.codam.nl>         +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/04/22 13:07:09 by whaffman      #+#    #+#                 */
/*   Updated: 2025/05/07 11:49:04 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include <fcntl.h>
#include <unistd.h>

#include "cub3d.h"

char	*read_map_file(const char *filename)
{
	int			fd;
	ssize_t		size;
	ssize_t		bytes_read;
	char		*buffer;

	fd = open(filename, O_RDONLY);
	if (fd == -1)
		return (NULL);
	size = get_file_size(filename);
	if (size == -1)
		return (close(fd), NULL);
	buffer = malloc(size * sizeof(char) + 1);
	if (!buffer)
		return (close(fd), NULL);
	bytes_read = read(fd, buffer, size);
	if (bytes_read == -1)
	{
		free(buffer);
		close(fd);
		return (NULL);
	}
	buffer[bytes_read] = '\0';
	close(fd);
	return (buffer);
}
