-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
71 lines (65 loc) · 2.01 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agaliste <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/13 23:37:11 by agaliste #+# #+# */
/* Updated: 2021/09/19 01:56:07 by agaliste ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
void *freeline(char *line)
{
free(line);
return (NULL);
}
int check_buffer(char *pos, char **line)
{
char *aux;
char *otro;
static char aux2[BUFFER_SIZE + 1];
aux = ft_strchr(pos, '\n');
otro = *line;
if (aux)
{
*aux = '\0';
*line = ft_strjoin(otro, pos);
free(otro);
ft_memcpy(aux2, aux + 1, ft_strlen(aux + 1));
ft_bzero(pos, BUFFER_SIZE + 1);
ft_memcpy(pos, aux2, ft_strlen(aux2));
ft_bzero(aux2, BUFFER_SIZE + 1);
otro = *line;
*line = ft_strjoin(otro, "\n");
free(otro);
return (1);
}
*line = ft_strjoin(otro, pos);
free(otro);
ft_bzero(pos, BUFFER_SIZE + 1);
return (0);
}
char *get_next_line(int fd)
{
char *line;
static char pos[BUFFER_SIZE + 1];
int rd;
line = malloc(sizeof(char) * BUFFER_SIZE + 1);
if (fd < 0 || fd > 256 || BUFFER_SIZE <= 0 || !line)
return (freeline(line));
ft_bzero(line, BUFFER_SIZE + 1);
if (check_buffer(pos, &line))
return (line);
rd = read(fd, pos, BUFFER_SIZE);
while (rd && rd != -1)
{
if (check_buffer(pos, &line))
return (line);
rd = read(fd, pos, BUFFER_SIZE);
}
if (line[0] == '\0')
return (freeline(line));
return (line);
}