-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
109 lines (100 loc) · 2.14 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
99
100
101
102
103
104
105
106
107
108
109
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atabiti <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/26 09:45:21 by atabiti #+# #+# */
/* Updated: 2022/03/25 12:58:26 by atabiti ### ########.fr */
/* */
/* ************************************************************************** */
#include "so_long.h"
static char *reader(char *b, int fd)
{
char *r;
int bytes;
r = malloc(BUFFER_SIZE + 1 * sizeof(char ));
if (!r)
return (NULL);
bytes = 1;
while (bytes > 0)
{
bytes = read(fd, r, BUFFER_SIZE);
if (bytes == 0)
break ;
if (bytes == -1)
{
free (r);
return (NULL);
}
r[bytes] = '\0';
b = ft_join(b, r);
if (ft_strchr(b, '\n'))
break ;
}
free (r);
return (b);
}
static char *grabline(char *b)
{
int i;
int a;
char *line;
i = 0;
while (b[i] && b[i] != '\n')
{
i++;
}
if (b[i] == '\n')
i++;
line = (char *) malloc (sizeof(char ) * i + 1);
a = 0;
while (a < i)
{
line[a] = b[a];
a++;
}
line[a] = '\0';
return (line);
}
static char *removeremaininig(char *b)
{
int i;
int a;
char *line;
i = 0;
while (b[i] && b[i] != '\n')
i++;
if (b[i] == '\n')
i++;
if (b[i] == '\0')
{
free (b);
return (NULL);
}
line = malloc(sizeof(char) * (ft_strlen(b) - i + 1));
if (!line)
return (NULL);
a = 0;
while (b[i])
line[a++] = b[i++];
line[a] = '\0';
free (b);
return (line);
}
char *get_next_line(int fd)
{
static char *b;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
{
exit(1);
}
b = reader(b, fd);
if (!b)
return (NULL);
line = grabline(b);
b = removeremaininig(b);
return (line);
}