-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
111 lines (100 loc) · 2.49 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: hunam <hunam@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/18 14:32:31 by etattevi #+# #+# */
/* Updated: 2023/03/23 16:41:32 by hunam ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
int chr_idx(const char *s, int c)
{
int i;
if (!s)
return (-1);
i = 0;
while (s[i])
{
if (s[i] == (char)c)
return (i);
i++;
}
if ((char)c == '\0')
return (i);
return (-1);
}
char *has_nl(char *saved[OPEN_MAX], int fd)
{
int nl_idx;
char *line;
char *rem;
nl_idx = chr_idx(saved[fd], '\n');
if (nl_idx != -1)
{
line = ft_substr(saved[fd], 0, nl_idx + 1);
rem = ft_substr(saved[fd], nl_idx + 1, ft_strlen(saved[fd]) - nl_idx);
free(saved[fd]);
saved[fd] = rem;
return (line);
}
return (NULL);
}
char *no_nl(char *saved[OPEN_MAX], int fd)
{
char *out;
out = NULL;
if (saved[fd])
{
if (saved[fd][0] != '\0')
out = ft_strdup(saved[fd]);
free(saved[fd]);
saved[fd] = NULL;
}
return (out);
}
char *ft_strjoin_free(char *s1, char *s2)
{
char *out;
size_t i;
size_t j;
if (!s1)
return (ft_strdup(s2));
if (!s2)
return (NULL);
out = malloc(sizeof(char) * (ft_strlen(s1) + ft_strlen(s2) + 1));
if (out == NULL)
return (NULL);
i = 0;
j = 0;
while (s1[j])
out[i++] = s1[j++];
j = 0;
while (s2[j])
out[i++] = s2[j++];
out[i] = '\0';
free(s1);
return (out);
}
char *get_next_line(int fd)
{
static char *saved[OPEN_MAX] = {NULL};
char buff[BUFFER_SIZE + 1];
char *line;
int just_read;
if (fd < 0 || BUFFER_SIZE < 1 || read(fd, NULL, 0) < 0)
return (NULL);
while (42)
{
line = has_nl(saved, fd);
if (line)
return (line);
just_read = read(fd, buff, BUFFER_SIZE);
if (just_read == 0 && chr_idx(saved[fd], '\n') == -1)
return (no_nl(saved, fd));
buff[just_read] = '\0';
saved[fd] = ft_strjoin_free(saved[fd], buff);
}
}