-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
104 lines (93 loc) · 2.45 KB
/
get_next_line.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: earnaud <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/17 12:48:55 by earnaud #+# #+# */
/* Updated: 2020/11/27 12:11:09 by earnaud ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_afterline(char *s)
{
char *temp;
if (!(ft_line(s) + 1))
return (NULL);
temp = ft_strdup(s + ft_line(s) + 1);
free(s);
return (temp);
}
int ft_check_error(char **line, int fd)
{
char buf[1];
if (fd < 0 || !line || read(fd, buf, 0) == -1 || BUFFER_SIZE < 1)
return (-1);
return (1);
}
int ft_sendline_next(char **line, char *rest)
{
size_t len;
if (ft_line(rest) == -1)
len = ft_strlen(rest);
else
len = ft_line(rest);
if (!(*line = malloc((len + 1) * sizeof(char *))))
return (-1);
ft_strlcpy(*line, rest, len + 1);
return (1);
}
int ft_read_buf(char **rest, char **line, int fd)
{
char buf[BUFFER_SIZE + 1];
int read_ret;
int ret;
ret = 1;
while (ft_line(*rest) == -1)
{
read_ret = read(fd, buf, BUFFER_SIZE);
if (!read_ret)
{
if (ft_line(*rest) == -1)
ret = 0;
break ;
}
buf[read_ret] = '\0';
if (!(*rest = ft_strjoin_sp(&*rest, buf)))
return (-1);
}
if (ft_sendline_next(line, *rest) == -1)
return (-1);
if (ft_line(*rest) + 1)
if (!(*rest = ft_afterline(*rest)))
return (-1);
return (ret);
}
int get_next_line(int fd, char **line)
{
static char *rest;
int ret;
ret = 1;
if (ft_check_error(line, fd) == -1)
return (-1);
if (!rest)
rest = ft_strdup("");
if (ft_line(rest) >= 0)
{
if (!(*line = malloc(ft_line(rest) * sizeof(char *))))
return (-1);
ft_strlcpy(*line, rest, ft_line(rest) + 1);
if (rest + ft_line(rest) + 1)
rest = ft_afterline(rest);
}
else
{
if (!(ret = ft_read_buf(&rest, line, fd)))
{
free(rest);
rest = NULL;
}
}
return (ret);
}