-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
80 lines (74 loc) · 2.03 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dalba-de <dalba-de@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/03 14:45:51 by dalba-de #+# #+# */
/* Updated: 2020/03/08 10:32:02 by dalba-de ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/cub3d.h"
static int fill_char(char **s, char **line, int fd)
{
int i;
char *aux;
i = 0;
while (s[fd][i] != '\n' && s[fd][i] != '\0')
i++;
if (s[fd][i] == '\n')
{
*line = ft_substr(s[fd], 0, i);
aux = ft_strdup(s[fd] + i + 1);
free(s[fd]);
s[fd] = aux;
}
else if (s[fd][i] == '\0')
{
*line = ft_strdup(s[fd]);
free(s[fd]);
s[fd] = NULL;
return (0);
}
return (1);
}
static int result(int r, char **s, char **line, int fd)
{
if (r < 0)
return (-1);
else if (r == 0 && (s[fd] == NULL || s[fd][0] == '\0'))
{
*line = ft_strdup("");
free(s[fd]);
s[fd] = NULL;
return (0);
}
return (fill_char(s, line, fd));
}
int get_next_line(int fd, char **line)
{
char *buffer;
int r;
char *aux;
static char *s[4096];
if (!(buffer = malloc(sizeof(char *) * BUFFER_SIZE + 1)) ||
fd < 0 || line == NULL)
return (-1);
while ((r = read(fd, buffer, BUFFER_SIZE)) > 0)
{
buffer[r] = '\0';
if (s[fd] == NULL)
s[fd] = ft_strdup(buffer);
else
{
aux = ft_strjoin(s[fd], buffer);
free(s[fd]);
s[fd] = aux;
}
if (ft_strchr(s[fd], '\n'))
break ;
}
free(buffer);
return (result(r, s, line, fd));
}