-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
124 lines (113 loc) · 2.62 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: blukasho <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/10 16:13:43 by blukasho #+# #+# */
/* Updated: 2018/11/28 13:10:22 by blukasho ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char **read_line(char **cur, int *len, const int fd)
{
char *buf;
char *tmp;
if ((buf = ft_strnew(BUFF_SIZE)))
{
if ((*len = read(fd, buf, BUFF_SIZE)) > 0)
{
tmp = *cur;
buf[*len] = '\0';
if ((*cur = ft_strjoin(*cur, buf)))
{
ft_strdel(&tmp);
ft_strdel(&buf);
return (cur);
}
}
free(buf);
return (cur);
}
return (NULL);
}
char **crt_lst_elem(t_lst **lst, const int fd)
{
t_lst *new;
if ((new = (t_lst *)malloc(sizeof(t_lst))))
{
new->str = NULL;
new->fd = fd;
new->next = *lst;
*lst = new;
return (&(*lst)->str);
}
return (NULL);
}
char **get_str(t_lst **lst, const int fd)
{
t_lst *tmp;
if (!*lst)
{
if ((*lst = (t_lst *)malloc(sizeof(t_lst))))
{
(*lst)->fd = fd;
(*lst)->str = NULL;
(*lst)->next = NULL;
return (&(*lst)->str);
}
return (NULL);
}
tmp = *lst;
while (tmp)
{
if (tmp->fd == fd)
return (&tmp->str);
tmp = tmp->next;
}
return (crt_lst_elem(lst, fd));
}
void cpy_line(char **cur, char **line)
{
char *tmp;
size_t nl;
tmp = *cur;
if (ft_strlen(*cur) == (nl = ft_strlen_chr(*cur, '\n')))
{
*line = ft_strdup(*cur);
*cur = ft_strnew(0);
free(tmp);
}
else
{
*line = ft_strndup(*cur, nl);
*cur = ft_strdup(*cur + ++nl);
free(tmp);
}
}
int get_next_line(const int fd, char **line)
{
int len;
static t_lst *lst;
char **cur;
len = 1;
if (fd < 0 || BUFF_SIZE <= 0 || (!lst && !get_str(&lst, fd)))
return (-1);
cur = get_str(&lst, fd);
if (!*cur && (*cur = ft_strnew(0)))
while (len > 0)
cur = read_line(cur, &len, fd);
if (len < 0)
{
ft_strdel(cur);
return (-1);
}
if (*cur[0] == '\0' && !(*line = NULL))
{
ft_strdel(cur);
return (0);
}
cpy_line(cur, line);
return (1);
}