-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
111 lines (102 loc) · 2.37 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
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
101
102
103
104
105
106
107
108
109
110
111
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lgaume <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/01 15:59:37 by lgaume #+# #+# */
/* Updated: 2023/11/01 15:59:39 by lgaume ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *get_next_line(int fd)
{
char *line;
static char *save[4096];
if (fd < 0 || BUFFER_SIZE <= 0 || fd >= 4096 || read(fd, 0, 0) < 0)
{
free_stash(save);
*save = NULL;
return (NULL);
}
save[fd] = read_save(fd, save[fd]);
if (!save[fd])
return (NULL);
line = newline(save[fd]);
save[fd] = clean_save(save[fd]);
return (line);
}
char *read_save(int fd, char *save)
{
char *buff;
int readed;
buff = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buff)
return (NULL);
readed = 1;
while (!ft_strchr(save, '\n') && readed != 0)
{
readed = read(fd, buff, BUFFER_SIZE);
if (readed == -1)
{
free(buff);
free(save);
return (NULL);
}
buff[readed] = '\0';
save = ft_strjoin(save, buff);
}
free(buff);
return (save);
}
char *newline(char *save)
{
int i;
char *str;
i = 0;
if (!save[i])
return (NULL);
while (save[i] && save[i] != '\n')
i++;
str = (char *)malloc(sizeof(char) * (i + 2));
if (!str)
return (NULL);
i = 0;
while (save[i] && save[i] != '\n')
{
str[i] = save[i];
i++;
}
if (save[i] == '\n')
{
str[i] = save[i];
i++;
}
str[i] = '\0';
return (str);
}
char *clean_save(char *save)
{
int i;
int j;
char *s;
i = 0;
while (save[i] && save[i] != '\n')
i++;
if (!save[i])
{
free(save);
return (NULL);
}
s = (char *)malloc(sizeof(char) * (ft_strlen(save) - 1 + 1));
if (!s)
return (NULL);
i++;
j = 0;
while (save[i])
s[j++] = save[i++];
s[j] = '\0';
free(save);
return (s);
}