aboutsummaryrefslogtreecommitdiffstats
path: root/libft/src/get_next_line.c
blob: 4ace77ac5d8eac6d75db4f7da0c6a4afde5f2622 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   get_next_line.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:07:20 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:07:20 by rbousset         ###   ########lyon.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[i] != '\0')
	{
		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);
		ft_memdel((void**)&tmp);
	}
	if (ret < 0)
	{
		ft_memdel((void**)&str);
		ft_memdel((void**)&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)
	{
		ft_memdel((void**)&str);
		return (-1);
	}
	return (0);
}

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

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