-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
89 lines (82 loc) · 2.08 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jikarunw <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/19 12:15:06 by jikarunw #+# #+# */
/* Updated: 2023/10/10 15:08:17 by jikarunw ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *ft_next_buffer(char **temp)
{
char *line;
char *ptr;
ptr = *temp;
while (*ptr && *ptr != '\n')
++ptr;
ptr += (*ptr == '\n');
line = ft_substr(*temp, 0, (size_t)(ptr - *temp));
if (!line)
{
free(*temp);
return (NULL);
}
ptr = ft_substr(ptr, 0, ft_strlen(ptr));
free(*temp);
*temp = ptr;
return (line);
}
static char *ft_read_buffer(char *temp, int fd, char *buf)
{
ssize_t r;
r = 1;
while (r && !ft_strchr(temp, '\n'))
{
r = read(fd, buf, BUFFER_SIZE);
if (r == -1)
{
free(buf);
free(temp);
return (NULL);
}
buf[r] = 0;
temp = ft_strjoin(temp, buf);
if (!temp)
{
free(buf);
return (NULL);
}
}
free(buf);
return (temp);
}
char *get_next_line(int fd)
{
static char *temp[FD_MAX];
char *buffer;
if (fd == -1 || BUFFER_SIZE < 1)
return (NULL);
if (!temp[fd])
temp[fd] = ft_strdup("");
if (!temp[fd])
return (NULL);
buffer = malloc(sizeof(*buffer) * (BUFFER_SIZE + 1));
if (!buffer)
{
free(temp[fd]);
return (NULL);
}
temp[fd] = ft_read_buffer(temp[fd], fd, buffer);
if (!temp[fd])
return (NULL);
if (!*temp[fd])
{
free(temp[fd]);
temp[fd] = NULL;
return (NULL);
}
return (ft_next_buffer(&temp[fd]));
}