-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
121 lines (111 loc) · 2.68 KB
/
get_next_line_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aaibar-h <aaibar-h@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/24 11:12:57 by aaibar-h #+# #+# */
/* Updated: 2023/03/24 11:55:20 by aaibar-h ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
void ft_lstadd_back(t_list **lst, t_list *new)
{
if (!lst)
return ;
if (new)
{
if (*lst)
{
while ((*lst)->next)
lst = &((*lst)->next);
(*lst)->next = new;
}
else
*lst = new;
}
}
char *ft_merge_strlst(t_list *lst)
{
char *str;
size_t i;
size_t j;
if (!lst)
return (NULL);
str = ft_calloc((ft_lstsize(lst) * BUFFER_SIZE) + 1, sizeof(char));
i = 0;
while (lst && *((unsigned char *) lst->content))
{
j = 0;
while (j < BUFFER_SIZE && ((unsigned char *) lst->content)[j])
{
str[i++] = ((unsigned char *) lst->content)[j++];
if (((unsigned char *) lst->content)[j - 1] == '\n')
break ;
}
lst = lst->next;
}
return (str);
}
static void mov_buf(char *buf)
{
size_t i;
size_t j;
i = 0;
j = 0;
while (i < BUFFER_SIZE)
{
if (i > 0 && buf[i - 1] == '\n')
break ;
i++;
}
while (buf[i])
buf[j++] = buf[i++];
while (buf[j])
buf[j++] = 0;
}
static size_t read_next_line(int fd, char *buf, t_list **buflst)
{
size_t i;
ssize_t res;
res = 1;
while (res > 0)
{
i = 0;
if (!buf[i])
res = read(fd, buf, BUFFER_SIZE);
while (i < BUFFER_SIZE && buf[i] && buf[i] != '\n')
i++;
ft_lstadd_back(buflst, ft_strlstnew(buf));
if (buf[i] == '\n')
break ;
ft_bzero(buf, BUFFER_SIZE);
}
return (res);
}
char *get_next_line(int fd)
{
static char *buf[MAX_FD];
char *final_str;
t_list *buflst;
ssize_t res;
buflst = NULL;
final_str = NULL;
if (fd < 0 || fd > MAX_FD)
return (NULL);
if (!buf[fd])
buf[fd] = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
res = read_next_line(fd, buf[fd], &buflst);
if ((*buf[fd] || ft_lstsize(buflst) > 0) && res >= 0)
final_str = ft_merge_strlst(buflst);
if (res <= 0)
{
free(buf[fd]);
buf[fd] = NULL;
}
else
mov_buf(buf[fd]);
ft_lstclear(&buflst, &free);
return (final_str);
}