-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
117 lines (106 loc) · 2.78 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agarijo- <agarijo-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/03 17:28:46 by agarijo- #+# #+# */
/* Updated: 2023/03/02 15:58:04 by agarijo- ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *ft_free(char *buffer, char *buf)
{
char *temp;
temp = ft_strjoin(buffer, buf);
free(buffer);
return (temp);
}
char *extract_before_bl(char *buf)
{
char *line;
int i;
i = 0;
if (!buf[i])
return (NULL);
while (buf[i] && buf[i] != '\n')
i++;
if (buf[i] == '\n')
i++;
line = ft_calloc((i + 1), sizeof(char));
if (!line)
return (NULL);
i = -1;
while (buf[++i] && buf[i] != '\n')
line[i] = buf[i];
if (buf[i] && buf[i] == '\n')
line[i] = '\n';
return (line);
}
char *extract_after_bl(char *buf)
{
int i;
int j;
char *line;
i = 0;
while (buf[i] && buf[i] != '\n')
i++;
if (!buf[i])
return (free(buf), NULL);
if (buf[i] == '\n')
i++;
line = ft_calloc((ft_strlen(buf) - i + 1), sizeof(char));
if (!line)
return (free(buf), NULL);
j = 0;
while (buf[i])
line[j++] = buf[i++];
free(buf);
return (line);
}
char *read_buffer(int fd, char *later)
{
char *buf;
int bytes_read;
int flag;
buf = ft_calloc((BUFFER_SIZE + 1), sizeof(char));
if (!buf)
return (free(later), NULL);
flag = 1;
while (flag)
{
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read == -1)
return (free(buf), free(later), NULL);
buf[bytes_read] = '\0';
if (bytes_read != 0)
later = ft_free(later, buf);
if (ft_strchr(buf, '\n') || bytes_read == 0 || !later)
flag = 0;
}
return (free(buf), later);
}
char *get_next_line(int fd)
{
static char *later[4096];
char *line;
if (!later[fd])
later[fd] = ft_calloc(1, 1);
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0 || !later[fd])
{
if (!later[fd])
return (NULL);
return (free(later[fd]), later[fd] = NULL, NULL);
}
later[fd] = read_buffer(fd, later[fd]);
if (later[fd])
{
line = extract_before_bl(later[fd]);
later[fd] = extract_after_bl(later[fd]);
if (line)
return (line);
return (free(later[fd]), later[fd] = NULL, line);
}
return (free(later[fd]), later[fd] = NULL, NULL);
}