-
Notifications
You must be signed in to change notification settings - Fork 10
/
get_next_line_bonus.c
70 lines (63 loc) · 1.92 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaeskim <jaeskim@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/03 17:48:48 by jaeskim #+# #+# */
/* Updated: 2021/02/01 23:11:30 by jaeskim ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static int storejoin(char **store, char *buf, ssize_t read_size)
{
char *tmp;
buf[read_size] = '\0';
if (0 != *store)
{
tmp = ft_strjoin(*store, buf);
free(*store);
}
else
tmp = ft_strndup(buf, read_size);
*store = tmp;
if (ft_strchr(*store, '\n'))
return (1);
return (0);
}
static int ft_check_line(char **store, char **line)
{
char *ptr;
char *tmp;
if ((ptr = ft_strchr(*store, '\n')))
{
*line = ft_strndup(*store, ptr - *store);
tmp = ft_strndup(ptr + 1, ft_strlen(ptr + 1));
free(*store);
*store = tmp;
return (1);
}
else
{
*line = *store;
*store = 0;
return (0);
}
}
int get_next_line(int fd, char **line)
{
static char *store[OPEN_MAX + 1];
ssize_t read_size;
char buf[BUFFER_SIZE + 1];
if (fd < 0 || fd > OPEN_MAX || !line || BUFFER_SIZE <= 0)
return (-1);
while ((read_size = read(fd, buf, BUFFER_SIZE)) >= 0)
{
if (storejoin(&store[fd], buf, read_size) || read_size == 0)
break ;
}
if (read_size < 0)
return (-1);
return (ft_check_line(&store[fd], line));
}