-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
77 lines (70 loc) · 2 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: antandre <antandre@student.42barcel> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/17 15:29:42 by antandre #+# #+# */
/* Updated: 2024/08/01 14:51:00 by antandre ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_last_line(char **saved)
{
char *res;
int i;
if (!(*saved) || !(*saved)[0])
return (NULL);
res = malloc(sizeof(char) * (ft_strlen(*saved) + 1));
if (!res)
return (NULL);
i = 0;
while ((*saved)[i] != '\0')
{
res[i] = (*saved)[i];
i++;
}
res[i] = '\0';
free(*saved);
*saved = NULL;
return (res);
}
char *ft_readfd(char **saved, int fd)
{
int readed;
char *buffer;
while (ft_isnewline((*saved)) == -1)
{
buffer = malloc(BUFFER_SIZE * sizeof(char));
if (!buffer)
return (NULL);
readed = read(fd, buffer, BUFFER_SIZE);
if (readed > 0)
readed = ft_strncat(saved, buffer, readed);
free(buffer);
if (readed == 0)
return (get_last_line(saved));
else if (readed == -1)
{
if ((*saved))
{
free((*saved));
(*saved) = NULL;
}
return (NULL);
}
}
return (ft_strtrim_jump(saved));
}
char *get_next_line(int fd)
{
static char *saved[1024];
if (fd < 0 || fd >= 1024 || BUFFER_SIZE <= 0)
return (NULL);
if (saved[fd] && ft_isnewline(saved[fd]) > -1)
return (ft_strtrim_jump(&saved[fd]));
else
return (ft_readfd(&saved[fd], fd));
return (NULL);
}