-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
95 lines (85 loc) · 2.34 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rde-lima <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/13 20:11:06 by rde-lima #+# #+# */
/* Updated: 2021/11/16 14:19:56 by rde-lima ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *ft_getline(int fd, char **buf, char **cache);
static ssize_t ft_readfile(int fd, char **buf, char **cache);
static char *ft_writecache(char **cache);
char *get_next_line(int fd)
{
static char *cache;
char *buf;
char *res;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
if (!cache)
cache = ft_strdup("");
buf = malloc(BUFFER_SIZE + 1);
if (!buf)
return (NULL);
res = ft_getline(fd, &buf, &cache);
free(buf);
buf = NULL;
return (res);
}
static char *ft_getline(int fd, char **buf, char **cache)
{
ssize_t size;
char *res;
size = ft_readfile(fd, buf, cache);
if (size <= 0 && !**cache)
{
free(*cache);
*cache = NULL;
return (NULL);
}
if (ft_strchr(*cache, '\n'))
return (ft_writecache(cache));
res = ft_strdup(*cache);
free(*cache);
*cache = NULL;
return (res);
}
static ssize_t ft_readfile(int fd, char **buf, char **cache)
{
ssize_t res;
char *tmp;
res = 1;
while (!ft_strchr(*cache, '\n') && res)
{
res = read(fd, *buf, BUFFER_SIZE);
if (res < 0)
return (res);
(*buf)[res] = '\0';
tmp = *cache;
*cache = ft_strjoin(tmp, *buf);
free(tmp);
tmp = NULL;
}
return (res);
}
static char *ft_writecache(char **cache)
{
ssize_t size;
char *res;
char *tmp;
size = 0;
while ((*cache)[size] != '\n' && (*cache)[size] != '\0')
++size;
if ((*cache)[size] == '\n')
++size;
tmp = *cache;
res = ft_substr(tmp, 0, size);
*cache = ft_strdup(&(*cache)[size]);
free(tmp);
tmp = NULL;
return (res);
}