summaryrefslogtreecommitdiffstats
path: root/libft/src/get_next_line.c
blob: 2b2f084936a517018850f14f9b0d2c095d7af36b (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
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
102
103
104
105
106
107
108
109
110
111
112
/* ************************************************************************** */
/*                                                          LE - /            */
/*                                                              /             */
/*   get_next_line.c                                  .::    .:/ .      .::   */
/*                                                 +:+:+   +:    +:  +:+:+    */
/*   By: rbousset <marvin@le-101.fr>                +:+   +:    +:    +:+     */
/*                                                 #+#   #+    #+    #+#      */
/*   Created: 2019/10/29 00:37:39 by rbousset     #+#   ##    ##    #+#       */
/*   Updated: 2019/10/29 00:37:41 by rbousset    ###    #+. /#+    ###.fr     */
/*                                                         /                  */
/*                                                        /                   */
/* ************************************************************************** */

#include <libft.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

static uint8_t
	ft_linecheck(const char *str)
{
	size_t	i;

	i = 0;
	while (str && str[i])
	{
		if (str[i] == '\n')
			return (1);
		i++;
	}
	return (0);
}

static size_t
	ft_linelen(const char *str)
{
	size_t	i;

	i = 0;
	while (str[i] != '\n' && str[i] != '\0')
		i++;
	return (i);
}

static int
	ft_linedup(int fd, char **str)
{
	char	*buff;
	char	*tmp;
	int		ret;

	if (!(buff = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char))))
		return (0);
	ret = 1;
	while (!ft_linecheck(*str) && (ret = read(fd, buff, BUFFER_SIZE)) > 0)
	{
		buff[ret] = '\0';
		tmp = *str;
		*str = ft_strjoin(tmp, buff);
		free(tmp);
	}
	if (ret < 0)
	{
		free(*str);
		free(buff);
		return (-1);
	}
	free(buff);
	return (ret);
}

static int
	ft_errchck(int fd, char **line, char **str)
{
	if (*str == NULL)
		*str = ft_nstr(0);
	if (fd < 0 || !line || BUFFER_SIZE <= 0)
	{
		free(*str);
		return (-1);
	}
	return (0);
}

int
	get_next_line(int fd, char **line)
{
	static char *str[1024];
	char		*tmp;
	size_t		i;
	int			ret;

	if (ft_errchck(fd, line, &str[fd]) == -1)
		return (-1);
	ret = ft_linedup(fd, &str[fd]);
	if (ret < 0)
		return (-1);
	i = ft_linelen(str[fd]);
	*line = ft_substr(str[fd], 0, i);
	tmp = str[fd];
	if (tmp[0] != '\0' && tmp)
		str[fd] = ft_strdup(tmp + i + (tmp[i] == '\n'));
	if (ret == 0 && ((str[fd] == NULL || str[fd][0] == '\0') || !ft_linecheck(str[fd])))
	{
		i = tmp[i];
		free(tmp);
		tmp = NULL;
		return (i == '\n');
	}
	free(tmp);
	return (1);
}