-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
executable file
·98 lines (89 loc) · 2.22 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pgueugno <pgueugno@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/27 11:12:16 by pgueugno #+# #+# */
/* Updated: 2020/12/02 16:44:17 by pgueugno ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_read_it(char **tmp, int fd)
{
int r;
char *buf;
char *p;
r = 1;
if (!(buf = malloc(sizeof(char) * (BUFFER_SIZE + 1))))
return (NULL);
while (!(ft_strchr(*tmp, '\n')) && r > 0)
{
(r = read(fd, buf, BUFFER_SIZE));
if (r)
{
buf[r] = '\0';
p = *tmp;
*tmp = ft_strjoin(*tmp, (char *)buf);
free(p);
}
}
free(buf);
buf = NULL;
return (*tmp);
}
char *ft_strncpy(char *dst, char *src, int n)
{
int i;
i = 0;
while (src[i] && i < n)
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
return (dst);
}
int ft_what_is_read(char **tmp, char **line)
{
char *p;
char *mem;
p = NULL;
if (ft_strchr(*tmp, '\n') == 0)
{
*line = ft_strdup(*tmp);
free(*tmp);
*tmp = NULL;
return (0);
}
else if (ft_strchr(*tmp, '\n') != 0)
{
mem = ft_strchr(*tmp, '\n');
if (!(*line = malloc(sizeof(char) * (mem - *tmp + 1))))
return (-1);
*line = ft_strncpy(*line, *tmp, (mem - *tmp));
p = *tmp;
*tmp = ft_strdup(mem + 1);
free(p);
return (1);
}
return (0);
}
int get_next_line(int fd, char **line)
{
static char *tmp = NULL;
if (line == NULL || fd < 0 || read(fd, tmp, 0) < 0 ||
BUFFER_SIZE < 0)
return (-1);
if (!tmp)
if (!(tmp = ft_strdup("")))
return (-1);
if (BUFFER_SIZE == 0)
{
*line = NULL;
return (0);
}
tmp = ft_read_it(&tmp, fd);
return (ft_what_is_read(&tmp, line));
}