-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
94 lines (84 loc) · 2.15 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: karisti- <karisti-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/21 12:05:51 by karisti- #+# #+# */
/* Updated: 2019/12/11 20:02:27 by karisti- ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
void del_buff(char **s)
{
if (s)
{
free(*s);
*s = NULL;
}
}
int get_end_pos(const char *s)
{
int i;
i = 0;
while (s[i] && s[i] != '\n')
i++;
return (i);
}
int put_line(char **s, char **line)
{
int end_pos;
char *tmp;
end_pos = get_end_pos(*s);
if ((*s)[end_pos] == '\n')
{
*line = ft_substr(*s, 0, end_pos);
tmp = ft_substr(*s, end_pos + 1, ft_strlen(*s));
free(*s);
*s = tmp;
return (1);
}
else
{
*line = ft_substr(*s, 0, ft_strlen(*s));
del_buff(s);
return (0);
}
}
int read_line(char **s, int fd, char **line)
{
char buff[BUFFER_SIZE + 1];
char *tmp;
int retrn;
while ((retrn = read(fd, buff, BUFFER_SIZE)) > 0)
{
buff[retrn] = '\0';
if (!s[fd])
s[fd] = ft_substr("", 0, 0);
tmp = ft_strjoin(s[fd], buff);
free(s[fd]);
s[fd] = tmp;
if (ft_strchr(s[fd], '\n'))
return (put_line(&s[fd], line));
}
if (retrn < 0)
return (-1);
else if (retrn == 0 && !s[fd])
{
*line = ft_substr("", 0, 0);
return (0);
}
else
return (put_line(&s[fd], line));
}
int get_next_line(int fd, char **line)
{
static char *saved[4096];
if (fd < 0 || !line)
return (-1);
if (saved[fd] && ft_strchr(saved[fd], '\n'))
return (put_line(&saved[fd], line));
else
return (read_line(saved, fd, line));
}