-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
73 lines (67 loc) · 2.05 KB
/
get_next_line_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: isousa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/01 16:59:18 by isousa #+# #+# */
/* Updated: 2021/03/01 18:36:46 by isousa ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static int ft_strsave(int fd, char **line, char **store)
{
int i;
char *temp;
i = 0;
while (store[fd][i] != '\n' && store[fd][i] != '\0')
i++;
if (store[fd][i] == '\n')
{
*line = ft_substr(store[fd], 0, i);
temp = ft_substr(store[fd], i + 1, ft_strlen(store[fd]) - i);
free(store[fd]);
store[fd] = temp;
return (1);
}
else
{
*line = ft_strdup(store[fd]);
free(store[fd]);
store[fd] = 0;
return (0);
}
}
static int ft_returns(int fd, char **line, char **store, int readcount)
{
if (readcount == -1)
return (-1);
if (!(readcount) && store[fd] == NULL)
{
*line = ft_strdup("");
return (0);
}
return (ft_strsave(fd, line, store));
}
int get_next_line(int fd, char **line)
{
static char *store[100000];
char buff[BUFFER_SIZE + 1];
char *temp;
int readcount;
if (fd < 0 || !line || BUFFER_SIZE <= 0)
return (-1);
while ((readcount = read(fd, buff, BUFFER_SIZE)) > 0)
{
buff[readcount] = '\0';
if (!store[fd])
store[fd] = ft_strdup("");
temp = ft_strjoin(store[fd], buff);
free(store[fd]);
store[fd] = temp;
if (ft_strchr(store[fd], '\n'))
break ;
}
return (ft_returns(fd, line, store, readcount));
}