This repository has been archived by the owner on Jun 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
100 lines (92 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ctherin <ctherin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/13 20:56:01 by ctherin #+# #+# */
/* Updated: 2022/06/17 17:20:11 by ctherin ### ########.fr */
/* */
/* ************************************************************************** */
#include"get_next_line_bonus.h"
char *ft_clear(char **ptr, int fd)
{
if (ptr[fd])
{
free(ptr[fd]);
ptr[fd] = NULL;
}
return (NULL);
}
void ft_terminate(char *buf, int rd_len)
{
buf[rd_len] = EOF_CHAR;
buf[rd_len + 1] = '\0';
}
char *ft_add_data(char *tmp, int fd)
{
char *new;
char *buf;
int rd_len;
buf = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buf)
return (NULL);
rd_len = read(fd, buf, BUFFER_SIZE);
if (rd_len == -1)
{
free(buf);
return (NULL);
}
buf[rd_len] = '\0';
if (rd_len < BUFFER_SIZE)
ft_terminate(buf, rd_len);
if (tmp)
{
new = ft_strjoin(tmp, buf);
free(buf);
free(tmp);
}
else
new = buf;
return (new);
}
char *ft_get_line(char *persistent, int *ln_end)
{
if (persistent[--*ln_end] == EOF_CHAR)
{
persistent[*ln_end] = '\0';
if (*ln_end > 0)
return (ft_substr(persistent, 0, *ln_end + 1));
else
return (NULL);
}
else
return (ft_substr(persistent, 0, *ln_end + 1));
}
char *get_next_line(int fd)
{
static char *persistent[MAX_FD];
char *ln;
char *tmp;
int ln_end;
if (fd < 0 || BUFFER_SIZE <= 0 || fd > MAX_FD)
return (NULL);
ln_end = ft_has_ending(persistent[fd]);
while (ln_end == 0)
{
persistent[fd] = ft_add_data(persistent[fd], fd);
if (!persistent[fd])
return (NULL);
ln_end = ft_has_ending(persistent[fd]);
}
tmp = persistent[fd];
ln = ft_get_line(persistent[fd], &ln_end);
if (!ln)
return (ft_clear(persistent, fd));
persistent[fd] = ft_strdup((char *)(persistent[fd] + ln_end + 1));
free(tmp);
if (!persistent[fd])
return (NULL);
return (ln);
}