-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_next_line.c
100 lines (90 loc) · 2.37 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
98
99
100
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gemartin <gemartin@student.42barc...> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/07 00:41:32 by gemartin #+# #+# */
/* Updated: 2022/07/07 16:41:52 by gemartin ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_free(char **str)
{
free(*str);
*str = NULL;
return (NULL);
}
char *clean_storage(char *storage)
{
char *new_storage;
char *ptr;
int len;
ptr = ft_strchr(storage, '\n');
if (!ptr)
{
new_storage = NULL;
return (ft_free(&storage));
}
else
len = (ptr - storage) + 1;
if (!storage[len])
return (ft_free(&storage));
new_storage = ft_substr(storage, len, ft_strlen(storage) - len);
ft_free(&storage);
if (!new_storage)
return (NULL);
return (new_storage);
}
char *new_line(char *storage)
{
char *line;
char *ptr;
int len;
ptr = ft_strchr(storage, '\n');
len = (ptr - storage) + 1;
line = ft_substr(storage, 0, len);
if (!line)
return (NULL);
return (line);
}
char *readbuf(int fd, char *storage)
{
int rid;
char *buffer;
rid = 1;
buffer = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buffer)
return (ft_free(&storage));
buffer[0] = '\0';
while (rid > 0 && !ft_strchr(buffer, '\n'))
{
rid = read (fd, buffer, BUFFER_SIZE);
if (rid > 0)
{
buffer[rid] = '\0';
storage = ft_strjoin(storage, buffer);
}
}
free(buffer);
if (rid == -1)
return (ft_free(&storage));
return (storage);
}
char *get_next_line(int fd)
{
static char *storage = {0};
char *line;
if (fd < 0)
return (NULL);
if ((storage && !ft_strchr(storage, '\n')) || !storage)
storage = readbuf (fd, storage);
if (!storage)
return (NULL);
line = new_line(storage);
if (!line)
return (ft_free(&storage));
storage = clean_storage(storage);
return (line);
}