-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
72 lines (65 loc) · 1.83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agras <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/02 15:08:54 by agras #+# #+# */
/* Updated: 2021/12/29 20:28:01 by agras ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <stdio.h>
#include <string.h>
char *cut_buff(char **left, int i)
{
char *line;
char *tmp;
line = ft_strndup(*left, i);
tmp = (*left);
(*left) += i;
*left = ft_strndup(*left, BUFFER_SIZE);
free(tmp);
return (line);
}
char *exit_func(char **left, char *buf)
{
char *tmp;
tmp = NULL;
if (*left)
{
if ((*left)[0])
tmp = ft_strndup(*left, ft_strlen(*left));
}
free(*left);
free(buf);
*left = NULL;
return (tmp);
}
char *get_next_line(int fd)
{
static char *left[1024];
char *buf;
int i;
int bytes_read;
i = 0;
if (left[fd])
{
while (left[fd][i])
{
if (left[fd][i] == '\n')
return (cut_buff(&left[fd], i + 1));
i++;
}
}
buf = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buf)
return (NULL);
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read <= 0)
return (exit_func(&left[fd], buf));
buf[bytes_read] = '\0';
left[fd] = ft_strjoin(left[fd], buf);
return (get_next_line(fd));
}