-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgnl.c
More file actions
89 lines (81 loc) · 2.14 KB
/
Copy pathgnl.c
File metadata and controls
89 lines (81 loc) · 2.14 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* gnl.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user <user@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/29 15:30:00 by user #+# #+# */
/* Updated: 2023/04/29 15:30:00 by user ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_gnl_free(char **p1, char **p2)
{
if (p1)
{
free(*p1);
*p1 = NULL;
}
if (p2)
{
free(*p2);
*p2 = NULL;
}
}
char *ft_gnl_trim_until_end(char **line, ssize_t rc)
{
char *rtn;
char *nl_idx;
rtn = NULL;
if (rc <= -1)
ft_gnl_free(&(*line), NULL);
if ((!line || !*line) && rc <= 0)
return (NULL);
nl_idx = ft_strchr(*line, '\n');
if (nl_idx)
{
rtn = ft_substr(*line, 0, nl_idx - *line + 1);
ft_memmove(*line, nl_idx + 1, ft_strlen(nl_idx + 1) + 1);
}
else if (*line)
{
rtn = ft_strdup(*line);
ft_gnl_free(&(*line), NULL);
}
if (!rtn || !rtn[0])
ft_gnl_free(&(*line), &rtn);
return (rtn);
}
static void gnl_join(char **dst, char *s)
{
char *tmp;
tmp = ft_strjoin(*dst, s);
free(*dst);
*dst = tmp;
}
char *get_next_line(int fd)
{
static char *line[FD_MAX];
char *buf;
ssize_t rc;
char *nl;
if (fd < 0 || fd >= FD_MAX || BUFFER_SIZE <= 0)
return (NULL);
rc = 0;
buf = (char *)malloc(sizeof(char) * (size_t)BUFFER_SIZE + 1);
nl = ft_strchr(line[fd], '\n');
while (!nl && buf)
{
rc = read(fd, buf, (size_t)BUFFER_SIZE);
if (rc <= 0)
break ;
buf[rc] = '\0';
nl = ft_strchr(buf, '\n');
gnl_join(&line[fd], buf);
if (!line[fd])
break ;
}
free(buf);
return (ft_gnl_trim_until_end(&line[fd], rc));
}