aboutsummaryrefslogtreecommitdiff
path: root/src/io/ft_next_line.c
blob: 59e245b147ab26000232f4609f40572e67cdbcc6 (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
#include "libft.h"

static int		st_find_newline(char *str)
{
	int i;

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

static int		st_free_return(char **ptr, char **ptr2, int ret)
{
	if (ptr != NULL)
	{
		free(*ptr);
		*ptr = NULL;
	}
	if (ptr2 != NULL)
	{
		free(*ptr2);
		*ptr2 = NULL;
	}
	return (ret);
}

static int		st_read_line(int fd, char **line, char *rest)
{
	int		ret;
	int		split_at;
	char	*buf;

	if ((buf = malloc(sizeof(char) * (FTNL_BUFFER_SIZE + 1))) == NULL)
		return (st_free_return(line, NULL, FTNL_STATUS_ERROR));
	while ((ret = read(fd, buf, FTNL_BUFFER_SIZE)) > 0)
	{
		buf[ret] = '\0';
		if ((split_at = st_find_newline(buf)) != -1)
		{
			ft_strcpy(rest, buf + split_at + 1);
			buf[split_at] = '\0';
			if ((*line = ft_strjoin_free(*line, buf, 1)) == NULL)
				return (st_free_return(&buf, NULL, FTNL_STATUS_ERROR));
			return (st_free_return(&buf, NULL, FTNL_STATUS_LINE));
		}
		if ((*line = ft_strjoin_free(*line, buf, 1)) == NULL)
			return (st_free_return(&buf, NULL, FTNL_STATUS_ERROR));
	}
	if (ret == -1)
		return (st_free_return(&buf, line, FTNL_STATUS_ERROR));
	return (st_free_return(&buf, NULL, ret));
}

/*
** if has rest:
**     if rest has newline:
**         push rest until newline in line, shift rest
**         return LINE_READ
**     else:
**         push rest in line
**
** while can read fd in buf
**     if buf has newline:
**         push buf until newline in line
**         push buf after newline in rest
**         return LINE_READ
**     push buf in line
**
** return FTNL_EOF
*/

int				ft_next_line(int fd, char **line)
{
	int			split_at;
	static char	rest[OPEN_MAX][FTNL_BUFFER_SIZE + 1] = {{0}};

	if (fd < 0 || fd > OPEN_MAX || line == NULL || FTNL_BUFFER_SIZE <= 0)
		return (FTNL_STATUS_ERROR);
	if ((*line = ft_strdup("")) == NULL)
		return (FTNL_STATUS_ERROR);
	if (rest[fd][0] == '\0')
		return (st_read_line(fd, line, rest[fd]));
	if ((split_at = st_find_newline(rest[fd])) != -1)
	{
		free(*line);
		if ((*line = (char*)malloc(sizeof(char) * (split_at + 1))) == NULL)
			return (FTNL_STATUS_ERROR);
		ft_strncpy(*line, rest[fd], split_at);
		(*line)[split_at] = '\0';
		ft_strcpy(rest[fd], rest[fd] + split_at + 1);
		return (FTNL_STATUS_LINE);
	}
	free(*line);
	if (!(*line = (char*)malloc(sizeof(char) * (ft_strlen(rest[fd]) + 1))))
		return (FTNL_STATUS_ERROR);
	ft_strcpy(*line, rest[fd]);
	rest[fd][0] = '\0';
	return (st_read_line(fd, line, rest[fd]));
}