-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_get_next_line.c
128 lines (117 loc) · 2.97 KB
/
ft_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
125
126
127
128
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aguemy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/07 13:49:00 by aguemy #+# #+# */
/* Updated: 2017/02/23 14:06:30 by aguemy ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_multi(t_list **lst, int fd)
{
t_list *lst1;
t_list *lst2;
t_fd *node;
lst1 = *lst;
while (lst1 && lst1->content && ((t_fd*)(lst1->content))->filed != fd)
lst1 = lst1->next;
if (lst1 && lst1->content && ((t_fd*)(lst1->content))->str)
return (((t_fd*)(lst1->content))->str);
else
{
if (!(node = (t_fd*)malloc(sizeof(t_fd))))
return (NULL);
if ((lst2 = ft_lstnew(node, 0)))
{
free(node);
((t_fd*)(lst2->content))->filed = fd;
((t_fd*)(lst2->content))->str = NULL;
ft_lstadd(lst, lst2);
}
return (NULL);
}
}
void ft_multi_up(t_list **lst, int fd, char *tmp1)
{
t_list *tmp;
tmp = *lst;
while (tmp && tmp->content && ((t_fd*)(tmp->content))->filed != fd)
tmp = tmp->next;
if (tmp && (t_fd*)(tmp->content))
((t_fd*)(tmp->content))->str = tmp1;
}
int ft_update(char **tmp1, char **tmp2, int *flag, int fd)
{
char buf[BUFF_SIZE + 1];
char *tmp3;
int lu;
while ((!(*tmp2)) && (*flag > 0))
{
lu = read(fd, buf, BUFF_SIZE);
if (lu == -1)
return (-1);
if (lu)
{
buf[lu] = '\0';
if (!(*tmp1))
*tmp1 = ft_strnew(1);
tmp3 = ft_strjoin(*tmp1, buf);
ft_strdel(tmp1);
if (!(*tmp1 = tmp3))
return (-1);
*tmp2 = ft_strchr(*tmp1, '\n');
(*flag)++;
}
else
*flag = (*flag) * -1;
}
return (1);
}
void line_update(char **tmp1, char **tmp2, char **line)
{
char *tmp3;
if (*tmp2)
{
(*line) = ft_strnew(*tmp2 - *tmp1 + 1);
(*line) = ft_strncpy(*line, *tmp1, *tmp2 - *tmp1);
tmp3 = ft_strdup(*tmp2 + 1);
ft_strdel(tmp1);
*tmp1 = tmp3;
}
else
{
(*line) = ft_strdup(*tmp1);
ft_strdel(tmp1);
*tmp1 = ft_strnew(1);
}
}
int get_next_line(int fd, char **line)
{
static t_list *lst = NULL;
char *tmp2;
int flag;
char *tmp1;
if (fd < 0)
return (-1);
flag = 1;
tmp2 = NULL;
if ((tmp1 = ft_multi(&lst, fd)))
tmp2 = (char*)ft_strchr(tmp1, '\n');
if (!tmp2)
if (ft_update(&tmp1, &tmp2, &flag, fd) == -1)
return (-1);
if (flag != -1 || (tmp1 && tmp1[0]))
{
line_update(&tmp1, &tmp2, line);
ft_multi_up(&lst, fd, tmp1);
return (1);
}
else
{
(*line) = NULL;
return (0);
}
}