-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
97 lines (86 loc) · 2.26 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jeshin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/17 17:14:01 by jeshin #+# #+# */
/* Updated: 2024/07/17 17:14:09 by jeshin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "libft.h"
static void *free_bkup(char **bkup)
{
if (!bkup)
return (0);
free(*bkup);
*bkup = 0;
return (0);
}
static char *make_bkup(char **bkup, size_t bkup_size)
{
size_t i;
char *ret;
char *tmp;
i = 0;
while ((*bkup)[i] && (*bkup)[i] != '\n')
i++;
ret = ft_substr(*bkup, 0, (i + 1));
if (!ret)
return ((char *)free_bkup(bkup));
if (bkup_size == i + 1)
tmp = 0;
else
tmp = ft_substr(*bkup, i + 1, bkup_size - (i + 1));
free(*bkup);
*bkup = tmp;
return (ret);
}
static char *_get_line(char **bkup)
{
char *ret;
size_t bkup_size;
bkup_size = ft_strlen(*bkup);
if (ft_strchr(*bkup, '\n'))
return (make_bkup(bkup, bkup_size));
if (!**bkup)
return ((char *)free_bkup(bkup));
ret = ft_substr(*bkup, 0, bkup_size);
free_bkup(bkup);
return (ret);
}
static int new_bkup(char **bkup, char *buf)
{
char *ret;
ret = ft_strjoin(*bkup, buf);
if (ret == 0)
{
free_bkup(bkup);
return (0);
}
free(*bkup);
*bkup = ret;
return (1);
}
char *get_next_line(int fd)
{
int rd_val;
char buf[BUFFER_SIZE + 1];
static char *bkup;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
while (1)
{
rd_val = read(fd, buf, BUFFER_SIZE);
if (rd_val < 0)
return ((char *)free_bkup(&bkup));
buf[rd_val] = 0;
if (new_bkup(&bkup, buf) == 0)
return (0);
if (ft_strchr(bkup, '\n') || rd_val < BUFFER_SIZE)
return (_get_line(&bkup));
}
return (0);
}