-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
65 lines (60 loc) · 1.92 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: codespace <codespace@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/04 01:43:31 by xjose #+# #+# */
/* Updated: 2024/07/25 18:14:04 by codespace ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *get_new_buffer(char *buffer, int fd)
{
char *tmp_buffer;
int rz;
rz = 0;
tmp_buffer = malloc(sizeof(char) * BUFFER_SIZE + 1);
while (rz < BUFFER_SIZE + 1)
tmp_buffer[rz++] = '\0';
rz = 1;
while (!ft_strchr(tmp_buffer, '\n') && rz != 0)
{
rz = read(fd, tmp_buffer, BUFFER_SIZE);
if (rz < 0 || (rz == 0 && buffer == NULL))
{
free(tmp_buffer);
return (NULL);
}
tmp_buffer[rz] = '\0';
if (buffer == NULL)
buffer = ft_strdup(tmp_buffer);
else
buffer = ft_strjoin(buffer, tmp_buffer);
}
free(tmp_buffer);
return (buffer);
}
char *get_next_line(int fd)
{
static char *buffer;
char *the_line;
char *rest_line;
int i;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buffer = get_new_buffer(buffer, fd);
if (buffer == NULL)
return (NULL);
i = 0;
while (buffer[i] != '\n' && buffer[i])
i++;
if (buffer[i] == '\n')
i += 1;
the_line = ft_substr(buffer, 0, i);
rest_line = ft_substr(buffer, i, ft_strlen(buffer) - i);
free(buffer);
buffer = rest_line;
return (the_line);
}