-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
133 lines (122 loc) · 2.88 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
122
123
124
125
126
127
128
129
130
131
132
133
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yrhiba <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/16 02:43:18 by yrhiba #+# #+# */
/* Updated: 2022/10/19 04:18:53 by yrhiba ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *read_content(char *content, int fd, int *r)
{
char *c;
c = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!c)
{
free(content);
return (NULL);
}
*c = '\0';
*r = read(fd, c, BUFFER_SIZE);
if (*r == -1)
{
free(c);
free(content);
return (NULL);
}
c[*r] = '\0';
if (*c)
content = ft_join(content, c);
free(c);
return (content);
}
void get_line_3(char *content, char *nw_content, char *line)
{
int i;
int j;
i = 0;
while (content[i] != '\n')
{
line[i] = content[i];
i++;
}
line[i++] = '\n';
line[i] = '\0';
j = 0;
while (content[i])
nw_content[j++] = content[i++];
nw_content[j] = '\0';
}
char *get_line_2(char **content, int index)
{
char *line;
char *nw_content;
line = (char *)malloc(sizeof(char) * (index + 2));
if (!line)
return (NULL);
nw_content = (char *)malloc(sizeof(char) * (ft_strlc(*content, 0) - index));
if (!nw_content)
{
free(line);
return (NULL);
}
get_line_3(*content, nw_content, line);
free(*content);
*content = nw_content;
if (content && *content == '\0')
return (free(content), *content = 0, line);
return (line);
}
char *get_line_1(char **content, int fd)
{
char *l;
int r;
r = 1;
l = (char *)malloc(sizeof(char));
if (!l)
return (NULL);
*l = '\0';
while (*content && ft_strlc(*content, 1) == -1 && r != 0)
*content = read_content(*content, fd, &r);
if (!*content)
{
free(l);
return (NULL);
}
if (r == 0)
{
l = ft_join(l, *content);
free(*content);
*content = 0;
if (*l == '\0')
return (free(l), l = NULL);
return (l);
}
return (free(l), l = get_line_2(content, ft_strlc(*content, 1)), l);
}
char *get_next_line(int fd)
{
static t_list *list;
t_list *tmp;
char *content;
char *line;
if (fd < 0)
return (NULL);
content = ft_get_content(&list, fd);
if (!content)
return (NULL);
line = get_line_1(&content, fd);
tmp = list;
while (tmp)
{
if (tmp->fd == fd)
tmp->content = content;
tmp = tmp->next;
}
if (!content)
delete_node(&list, fd);
return (line);
}