-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
126 lines (115 loc) · 2.83 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aderison <aderison@student.s19.be> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/10 19:38:19 by aderison #+# #+# */
/* Updated: 2024/04/13 11:17:19 by aderison ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *ft_join_free(char **s1, char *s2)
{
char *ret;
if (*s1)
ret = ft_strjoin(*s1, s2);
else
ret = ft_strjoin("", s2);
free(*s1);
return (ret);
}
static char *get_buffer_file(int fd, char **buffer, char **tmp_buffer)
{
int bytes;
while (!(*tmp_buffer) || !ft_strchr(*buffer, '\n'))
{
bytes = read(fd, *tmp_buffer, BUFFER_SIZE);
if (bytes < 0)
{
free(*tmp_buffer);
free(*buffer);
*buffer = NULL;
return (NULL);
}
if (bytes == 0)
break ;
(*tmp_buffer)[bytes] = '\0';
*buffer = ft_join_free(buffer, *tmp_buffer);
if (!(*buffer))
{
free(*tmp_buffer);
return (NULL);
}
}
free(*tmp_buffer);
return (*buffer);
}
static char *get_line(char *buffer)
{
char *line;
int len;
if (!buffer)
return (NULL);
len = 0;
while (buffer[len] && buffer[len] != '\n')
len++;
if (buffer[len] == '\n')
len++;
line = (char *)malloc(len + 1);
if (!line)
return (NULL);
ft_strlcpy(line, buffer, (size_t)(len + 1));
return (line);
}
static char *clean_buffer(char *line, char **buffer)
{
int start;
int end;
char *new_buffer;
if (!line || !buffer)
return (NULL);
start = ft_strlen(line);
end = ft_strlen(*buffer);
if (end - start < 0 || end - start == 0)
{
free(*buffer);
return (NULL);
}
new_buffer = (char *)malloc(end - start + 1);
if (!new_buffer)
{
free(*buffer);
return (NULL);
}
ft_strlcpy(new_buffer, *buffer + start, end - start + 1);
free(*buffer);
return (new_buffer);
}
char *get_next_line(int fd)
{
static char *buffer;
char *tmp_buffer;
char *line;
if (fd < 0 || fd > OPEN_MAX || BUFFER_SIZE <= 0
|| BUFFER_SIZE >= INT32_MAX)
return (NULL);
tmp_buffer = (char *)malloc(BUFFER_SIZE + 1);
if (!tmp_buffer)
{
free(buffer);
buffer = NULL;
return (NULL);
}
buffer = get_buffer_file(fd, &buffer, &tmp_buffer);
line = get_line(buffer);
if (!line)
{
free(buffer);
buffer = NULL;
return (NULL);
}
buffer = clean_buffer(line, &buffer);
return (line);
}