-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
76 lines (69 loc) · 1.99 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: conguyen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/27 17:05:21 by conguyen #+# #+# */
/* Updated: 2022/02/25 08:47:45 by conguyen ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "wordle.h"
static int ft_get_line(char **saved, char **line, int ret)
{
int c;
char *temp;
if (ret == 0 && *saved == NULL)
return (0);
c = 0;
while ((*saved)[c] != '\0' && (*saved)[c] != '\n')
c++;
if ((*saved)[c] == '\n')
{
*line = ft_strsub(*saved, 0, c);
temp = ft_strdup(&((*saved)[c + 1]));
free(*saved);
*saved = temp;
}
else
{
*line = ft_strdup(*saved);
ft_strdel(saved);
return (0);
}
return (1);
}
static int ft_save_buffer(char *buf, char **line, int ret, int fd)
{
char *temp;
static char *saved[MAX_FD];
while (ret)
{
ret = read(fd, buf, BUFF_SIZE);
if (ret < 0)
return (-1);
buf[ret] = '\0';
if (saved[fd] != NULL)
{
temp = ft_strjoin(saved[fd], buf);
free(saved[fd]);
saved[fd] = temp;
}
else
saved[fd] = ft_strdup(buf);
if (ft_strchr(saved[fd], '\n') != NULL)
break ;
}
return (ft_get_line(&saved[fd], line, ret));
}
int get_next_line(const int fd, char **line)
{
char buf[BUFF_SIZE + 1];
int ret;
if (fd < 0 || line == NULL || BUFF_SIZE <= 0)
return (-1);
ret = 1;
return (ft_save_buffer(buf, line, ret, fd));
}