-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
95 lines (85 loc) · 2.38 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
94
95
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: viforget <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/18 09:25:12 by viforget #+# #+# */
/* Updated: 2019/12/19 14:00:17 by viforget ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static size_t find_n(char str[])
{
size_t n;
n = 0;
while (str && str[n] && str[n] != SEP)
n++;
return (n);
}
static char *ft_strjoind(char *s1, char const *s2)
{
int i;
int i2;
char *str;
int len;
i = 0;
i2 = 0;
if (!s2)
return (NULL);
len = ft_strlen(s1) + find_n((char *)s2);
if (!(str = (char *)malloc(sizeof(char) * (len + 1))))
return (NULL);
while (s1 && s1[i] != '\0')
str[i2++] = s1[i++];
i = 0;
while (s2[i] != '\0' && s2[i] != SEP)
str[i2++] = s2[i++];
str[i2] = '\0';
free(s1);
return (str);
}
static int fill_zero(char str[], ssize_t nb)
{
if (nb >= 0)
while (nb <= BUFFER_SIZE)
str[nb++] = 0;
return (0);
}
static void cut_str(char str[], size_t n)
{
size_t i;
i = 0;
while (n < BUFFER_SIZE)
str[i++] = str[n++];
while (i < BUFFER_SIZE)
str[i++] = 0;
}
int get_next_line(int fd, char **line)
{
static char buf[OPEN_MAX][BUFFER_SIZE + 1];
ssize_t rd;
if (fd < 0 || fd > OPEN_MAX || !line || BUFFER_SIZE <= 0)
return (-1);
*line = ft_strjoind(NULL, buf[fd]);
rd = BUFFER_SIZE;
if (find_n(buf[fd]) != ft_strlen(buf[fd]))
{
cut_str(buf[fd], find_n(buf[fd]) + 1);
return (1);
}
while (rd == BUFFER_SIZE && (rd = read(fd, buf[fd], BUFFER_SIZE)))
{
if (rd < 0)
return (-1);
fill_zero(buf[fd], rd);
*line = ft_strjoind(*line, buf[fd]);
if (rd == BUFFER_SIZE)
rd = find_n(buf[fd]);
}
if (find_n(buf[fd]) == ft_strlen(buf[fd]))
return (fill_zero(buf[fd], 0));
cut_str(buf[fd], find_n(buf[fd]) + 1);
return (1);
}