-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
105 lines (96 loc) · 2.49 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cabo-ram <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/04 09:19:42 by cabo-ram #+# #+# */
/* Updated: 2024/11/13 08:21:51 by cabo-ram ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static char *rest(char *pile)
{
size_t i;
size_t j;
char *temp;
i = 0;
while (pile[i] && pile[i] != '\n')
i++;
if (!pile[i])
return (free(pile), NULL);
temp = (char *)malloc(sizeof(char) * (ft_strlen(pile) - i + 1));
if (temp == NULL)
return (NULL);
i++;
j = 0;
while (pile[i])
temp[j++] = pile[i++];
temp[j] = '\0';
free(pile);
return (temp);
}
static char *get_new(char *pile)
{
size_t i;
char *new;
i = 0;
if (!pile[i])
return (NULL);
while (pile[i] && pile[i] != '\n')
i++;
if (pile[i] == '\n')
i++;
new = (char *)malloc(i + 1);
if (new == NULL)
return (NULL);
i = -1;
while (i++, pile[i] && pile[i] != '\n')
new[i] = pile[i];
if (pile[i] == '\n')
{
new[i] = pile[i];
i++;
}
new[i] = '\0';
return (new);
}
static char *join_pile(int fd, char *pile)
{
int bytes;
char *buffer;
char *temp;
bytes = 1;
buffer = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (buffer == NULL)
return (free(pile), pile = NULL);
while (!ft_strchr(pile, '\n') && bytes > 0)
{
bytes = read(fd, buffer, BUFFER_SIZE);
if (bytes < 0)
return (free(buffer), free(pile), pile = NULL);
if (bytes == 0)
break ;
buffer[bytes] = '\0';
temp = ft_strjoin(pile, buffer);
free (pile);
pile = temp;
}
return (free(buffer), pile);
}
char *get_next_line(int fd)
{
static char *pile[1024];
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
if (pile[fd] == NULL)
pile[fd] = ft_strdup("");
pile[fd] = join_pile(fd, &pile[fd][0]);
if (pile[fd] == NULL)
return (NULL);
line = get_new(&pile[fd][0]);
pile[fd] = rest(&pile[fd][0]);
return (line);
}