-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
81 lines (70 loc) · 2.19 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hirenpat <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/07 12:13:33 by hirenpat #+# #+# */
/* Updated: 2019/05/11 17:50:39 by hirenpat ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int ft_read(int fd, char *buffer, int buff_size)
{
int return_value;
return_value = read(fd, buffer, buff_size);
buffer[return_value] = '\0';
return (return_value);
}
int ft_strchrn(char *str, int c)
{
int i;
i = 0;
while (str[i] != '\0' && str[i] != (char)c)
i++;
return (i);
}
void ft_strtrim_todest(char **dest, char **src, int start, int end)
{
char *temp;
*dest = ft_strsub(*src, start, end);
temp = ft_strdup(*src + end + 1);
free(*src);
*src = temp;
if (*src[0] == '\0')
ft_strdel(src);
}
void ft_strappend(char **str, char *sub)
{
char *temp;
temp = ft_strjoin(*str, sub);
free(*str);
*str = temp;
}
int get_next_line(const int fd, char **line)
{
static char *hm[MAX_FD];
char b[BUFF_SIZE + 1];
int i;
int end;
if (INVALID_FD(fd) == 1 || line == NULL || read(fd, b, 0) < 0)
return (-1);
if (hm[fd] == NULL)
hm[fd] = ft_strnew(1);
while (ft_strchr(hm[fd], '\n') == 0 && (i = ft_read(fd, b, BUFF_SIZE)) > 0)
ft_strappend(&hm[fd], b);
if (i == 0 && (hm[fd] == NULL || hm[fd][0] == '\0'))
return (0);
end = ft_strchrn(hm[fd], '\n');
if (hm[fd][end] == '\n')
ft_strtrim_todest(&*line, &hm[fd], 0, end);
else
{
if (BUFF_SIZE == i)
return (get_next_line(fd, line));
*line = ft_strdup(hm[fd]);
ft_strdel(&hm[fd]);
}
return (1);
}