-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
103 lines (96 loc) · 2.59 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mduran-l <mduran-l@student.42malaga.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/02/01 11:27:07 by mduran-l #+# #+# */
/* Updated: 2024/02/15 14:08:51 by mduran-l ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *freeall(char **s1, char **s2)
{
if (!s1)
return (NULL);
if (*s1 != NULL)
free(*s1);
*s1 = NULL;
if (!s2)
return (NULL);
if (*s2 != NULL)
free(*s2);
*s2 = NULL;
return (NULL);
}
static char *extract_line(char *buff)
{
char *line;
int i;
if (!buff)
return (NULL);
i = ft_linelen(buff) + 1;
if (!i)
i = ft_strlen(buff);
if (!i)
return (freeall(&buff, NULL));
line = ft_calloc(i + 1, sizeof(char));
if (!line)
return (freeall(&buff, NULL));
i = -1;
while (buff[++i] && buff[i] != '\n')
line[i] = buff[i];
if (buff[i] == '\n')
line[i] = '\n';
return (line);
}
static char *clear_buffer(char *line, char *buff)
{
size_t i;
size_t j;
size_t s;
char *cleared;
if (!line)
return (NULL);
if (!buff)
return (freeall(&line, NULL));
s = ft_strlen(buff);
i = ft_strlen(line);
if (!(s - i))
return (freeall(&buff, NULL));
cleared = ft_calloc(s - i + 1, sizeof(char));
if (!cleared)
return (freeall(&buff, NULL));
j = 0;
while (buff[i])
cleared[j++] = buff[i++];
freeall(&buff, NULL);
return (cleared);
}
char *get_next_line(int fd)
{
static char *buff[FD_MAX] = {0};
char *line;
int fd_read;
if (fd < 0 || !BUFFER_SIZE)
return (NULL);
line = (char *)ft_calloc(1 + BUFFER_SIZE, sizeof(char));
if (!line)
return (freeall(&buff[fd], NULL));
fd_read = 1;
while (fd_read && ft_linelen(line) < 0)
{
ft_bzero(line, (BUFFER_SIZE + 1) * sizeof(char));
fd_read = read(fd, line, BUFFER_SIZE);
if (fd_read < 0)
return (freeall(&line, &buff[fd]));
buff[fd] = ft_strjoin(buff[fd], line);
if (!buff[fd])
return (freeall(&line, NULL));
}
freeall(&line, NULL);
line = extract_line(buff[fd]);
buff[fd] = clear_buffer(line, buff[fd]);
return (line);
}