-
Notifications
You must be signed in to change notification settings - Fork 8
/
get_next_line_bonus.c
108 lines (97 loc) · 2.41 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jdecorte <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/19 11:09:06 by jdecorte #+# #+# */
/* Updated: 2021/10/19 11:59:29 by jdecorte ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *fr_free(char *buffer, char *buf)
{
char *temp;
temp = ft_strjoin(buffer, buf);
free(buffer);
return (temp);
}
char *ft_next(char *buffer)
{
int i;
int j;
char *line;
i = 0;
while (buffer[i] && buffer[i] != '\n')
i++;
if (!buffer[i])
{
free(buffer);
return (NULL);
}
line = ft_calloc((ft_strlen(buffer) - i + 1), sizeof(char));
i++;
j = 0;
while (buffer[i])
line[j++] = buffer[i++];
free(buffer);
return (line);
}
char *ft_line(char *buffer)
{
char *line;
int i;
i = 0;
if (!buffer[i])
return (NULL);
while (buffer[i] && buffer[i] != '\n')
i++;
line = ft_calloc(i + 2, sizeof(char));
i = 0;
while (buffer[i] && buffer[i] != '\n')
{
line[i] = buffer[i];
i++;
}
if (buffer[i] && buffer[i] == '\n')
line[i++] = '\n';
return (line);
}
char *read_file(int fd, char *res)
{
char *buffer;
int byte_read;
if (!res)
res = ft_calloc(1, 1);
buffer = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
byte_read = 1;
while (byte_read > 0)
{
byte_read = read(fd, buffer, BUFFER_SIZE);
if (byte_read == -1)
{
free(buffer);
return (NULL);
}
buffer[byte_read] = 0;
res = fr_free(res, buffer);
if (ft_strchr(buffer, '\n'))
break ;
}
free(buffer);
return (res);
}
char *get_next_line(int fd)
{
static char *buffer[OPEN_MAX];
char *line;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
buffer[fd] = read_file(fd, buffer[fd]);
if (!buffer[fd])
return (NULL);
line = ft_line(buffer[fd]);
buffer[fd] = ft_next(buffer[fd]);
return (line);
}