aboutsummaryrefslogtreecommitdiff
path: root/src/io/ft_getfile.c
blob: d3f697c9ff8c4dee1d6686002de727ad56b7d798 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_getfile.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: charles <charles.cabergs@gmail.com>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/05/11 09:52:32 by charles           #+#    #+#             */
/*   Updated: 2020/05/11 16:09:31 by charles          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft_io.h"

/*
** \brief      Read a file in a memory buffer
** \param fd   File descriptor to read from
** \param mem  Pointer to mem struct (buffer and buffer size)
** \return     -1 on error, 0 otherwise
*/

int	ft_getfile(int fd, t_ftmem *mem)
{
	char	buf[FT_GETFILE_BUFFER_SIZE];
	int		ret;

	if (fd < 0 || fd > OPEN_MAX || mem == NULL
		|| (mem->data = malloc(1)) == NULL)
		return (-1);
	mem->size = 0;
	while ((ret = read(fd, buf, FT_GETFILE_BUFFER_SIZE)) > 0)
	{
		if ((mem->data = ft_memjoinf1(mem->data, mem->size, buf, ret)) == NULL)
			return (-1);
		mem->size += ret;
	}
	if (ret == -1)
		free(mem->data);
	return (ret);
}