-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
78 lines (72 loc) · 2.21 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rtroll <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/04 17:33:11 by rtroll #+# #+# */
/* Updated: 2018/12/05 18:07:56 by rtroll ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static int ft_check_null(char **next_line, char **line)
{
if (*line == NULL)
{
ft_strdel(next_line);
return (1);
}
return (0);
}
static int ft_new_line(char **next_line, char **line)
{
char *tmp;
int size;
size = 0;
while (next_line[0][size] != '\n' && next_line[0][size] != '\0')
size++;
if (next_line[0][size] == '\n')
{
*line = ft_strsub(next_line[0], 0, size);
if (ft_check_null(next_line, line) == 1)
return (-1);
tmp = ft_strdup(next_line[0] + size + 1);
ft_strdel(next_line);
CHECK_PTR(tmp);
next_line[0] = tmp;
}
else if (next_line[0][size] == '\0')
{
*line = ft_strdup(next_line[0]);
ft_strdel(next_line);
CHECK_PTR(*line);
}
return (1);
}
int get_next_line(const int fd, char **line)
{
char buff[BUFF_SIZE + 1];
static char *next_line = NULL;
int ret;
char *tmp;
if (fd < 0 || line == NULL || read(fd, buff, 0) < 0)
return (-1);
while ((ret = read(fd, buff, BUFF_SIZE)) > 0)
{
buff[ret] = '\0';
if (next_line == NULL)
next_line = ft_strnew(0);
if (next_line == NULL)
return (-1);
tmp = ft_strjoin(next_line, buff);
ft_strdel(&next_line);
CHECK_PTR(tmp);
next_line = tmp;
if (ft_strchr(buff, '\n') != NULL)
break ;
}
if (ret == 0 && (next_line == NULL || next_line[0] == '\0'))
return (0);
return (ft_new_line(&next_line, line));
}