-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
86 lines (79 loc) · 2.03 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cfischer <cfischer@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/23 18:40:36 by cfischer #+# #+# */
/* Updated: 2022/04/25 17:03:54 by cfischer ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *join_line(int nlp, char **buffer)
{
char *tmp;
char *res;
if (nlp <= 0)
{
if (**buffer == 0)
{
free(*buffer);
*buffer = NULL;
return (NULL);
}
res = *buffer;
*buffer = NULL;
return (res);
}
tmp = ft_substr(*buffer, nlp, BUFFER_SIZE);
res = *buffer;
res[nlp] = 0;
*buffer = tmp;
return (res);
}
char *read_line(int fd, char **buffer, char *tmp)
{
int nbytes;
char *nl;
char *nstr;
nbytes = 0;
nstr = NULL;
nl = ft_strchr(*buffer, '\n');
while (nl == NULL)
{
nbytes = read(fd, tmp, BUFFER_SIZE);
if (nbytes <= 0)
{
return (join_line(nbytes, buffer));
}
tmp[nbytes] = 0;
nstr = ft_strjoin(*buffer, tmp);
free(*buffer);
*buffer = nstr;
nl = ft_strchr(*buffer, '\n');
}
return (join_line(nl - *buffer + 1, buffer));
}
char *get_next_line(int fd)
{
char *tmp;
char *res;
static char *buffer[256];
if (fd < 0 || BUFFER_SIZE <= 0 || fd > 256)
{
return (NULL);
}
tmp = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (tmp == NULL)
{
return (NULL);
}
if (!buffer[fd])
{
buffer[fd] = ft_strdup("");
}
res = read_line(fd, &buffer[fd], tmp);
free (tmp);
return (res);
}