-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
98 lines (89 loc) · 2.4 KB
/
get_next_line.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfilloux <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/07 13:20:53 by lfilloux #+# #+# */
/* Updated: 2021/11/13 13:45:02 by lfilloux ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *reader(int fd)
{
char *buffer;
int readv;
buffer = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buffer)
return (NULL);
readv = read(fd, buffer, BUFFER_SIZE);
if (readv < 0)
{
free (buffer);
return (NULL);
}
buffer[readv] = '\0';
return (buffer);
}
static char *continuereading(char *save, int fd)
{
char *new_buffer;
char *dest;
dest = reader(fd);
if (!dest)
return (NULL);
if (!dest[0])
{
free (dest);
return (save);
}
if (!save)
return (dest);
new_buffer = ft_strjoin(save, dest);
free (save);
free (dest);
return (new_buffer);
}
static char *findnl(char *save, char *line)
{
char *new_buffer;
size_t size_len;
if (!save || !line)
return (NULL);
size_len = ft_strlen(line);
if (size_len == ft_strlen(save))
{
free (save);
return (NULL);
}
new_buffer = ft_substr(save, size_len, (ft_strlen(save) - size_len));
free (save);
return (new_buffer);
}
char *get_next_line(int fd)
{
static char *save[4096];
char *line;
size_t lensize;
if (fd < 0 || BUFFER_SIZE < 1)
return (NULL);
line = 0;
if (ft_strchr(save[fd], '\n') == -1)
{
lensize = ft_strlen(save[fd]);
save[fd] = continuereading(save[fd], fd);
if (lensize == ft_strlen(save[fd]) && save[fd])
line = ft_substr(save[fd], 0, lensize);
}
if (!save[fd])
return (NULL);
if (!line && ft_strchr(save[fd], '\n') != -1)
line = ft_substr(save[fd], 0, (ft_strchr(save[fd], '\n') + 1));
if (line)
{
save[fd] = findnl(save[fd], line);
return (line);
}
return (get_next_line(fd));
}