-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
93 lines (84 loc) · 2.13 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ehafidi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/26 14:02:12 by ehafidi #+# #+# */
/* Updated: 2019/11/29 13:24:47 by ehafidi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *ft_strcpy(char *dest, char *src)
{
int i;
int j;
i = 0;
j = 0;
while (src[j])
{
dest[i] = src[j];
i++;
j++;
}
dest[i] = '\0';
return (dest);
}
int ft_check_nl(char *str)
{
int i;
i = 0;
if (!str)
return (-1);
while (str[i])
{
if (str[i] == '\n')
return (i);
i++;
}
return (-1);
}
char *ft_readline(char *line, int fd)
{
char *buf;
int ret;
ret = 1;
if (!(buf = malloc(sizeof(*buf) * (BUFFER_SIZE + 1))))
return (NULL);
while (ft_check_nl(line) < 0 && (ret = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[ret] = '\0';
if (!(line = ft_strjoin(line, buf)))
{
free(buf);
return (NULL);
}
if (ft_check_nl(line) >= 0)
break ;
}
if (ret < 0)
return (NULL);
free(buf);
return (line);
}
int get_next_line(int fd, char **line)
{
static char rest[OPEN_MAX][BUFFER_SIZE + 1];
int nl;
if (fd < 0 || line == 0 || BUFFER_SIZE < 1 || fd > OPEN_MAX)
return (-1);
if (!(*line = ft_strdup(rest[fd])))
return (-1);
if (!(*line = ft_readline(*line, fd)))
return (-1);
if ((nl = ft_check_nl(*line)) >= 0 || (ft_check_nl(rest[fd])) >= 0)
{
ft_strcpy(rest[fd], *line + nl + 1);
if (!(*line = ft_substr(*line, 0, nl)))
return (-1);
return (1);
}
rest[fd][0] = '\0';
return (0);
}