This repository has been archived by the owner on Nov 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_next_line.c
127 lines (116 loc) · 2.67 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcombeau <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/04 14:06:51 by mcombeau #+# #+# */
/* Updated: 2021/12/19 03:32:49 by mcombeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_before_newline(const char *s)
{
char *res;
int i;
i = 0;
while (s[i] != '\0' && s[i] != '\n')
i++;
if (s[i] != '\0' && s[i] == '\n')
i++;
res = ft_malloc_zero(i + 1, sizeof * res);
if (!res)
return (NULL);
i = 0;
while (s[i] != '\0' && s[i] != '\n')
{
res[i] = s[i];
i++;
}
if (s[i] == '\n')
{
res[i] = s[i];
i++;
}
return (res);
}
char *get_after_newline(const char *s)
{
char *res;
int i;
int j;
j = 0;
while (s && s[j])
j++;
i = 0;
while (s[i] != '\0' && s[i] != '\n')
i++;
if (s[i] != '\0' && s[i] == '\n')
i++;
res = ft_malloc_zero((j - i) + 1, sizeof * res);
if (!res)
return (NULL);
j = 0;
while (s[i + j])
{
res[j] = s[i + j];
j++;
}
return (res);
}
void ft_read_line(int fd, char **keep, char **tmp)
{
char *buf;
int r;
buf = malloc(sizeof * buf * (BUFFER_SIZE + 1));
if (!buf)
return ;
r = 1;
while (r > 0)
{
r = read(fd, buf, BUFFER_SIZE);
if (r == -1)
{
ft_free_strs(&buf, keep, tmp);
return ;
}
buf[r] = '\0';
*tmp = ft_strdup(*keep);
ft_free_strs(keep, 0, 0);
*keep = join_strs(*tmp, buf);
ft_free_strs(tmp, 0, 0);
if (contains_newline(*keep))
break ;
}
ft_free_strs(&buf, 0, 0);
}
char *ft_parse_line(char **keep, char **tmp)
{
char *line;
*tmp = ft_strdup(*keep);
ft_free_strs(keep, 0, 0);
*keep = get_after_newline(*tmp);
line = get_before_newline(*tmp);
ft_free_strs(tmp, 0, 0);
return (line);
}
char *get_next_line(int fd)
{
static char *keep = NULL;
char *tmp;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
line = NULL;
tmp = NULL;
ft_read_line(fd, &keep, &tmp);
if (keep != NULL && *keep != '\0')
line = ft_parse_line(&keep, &tmp);
if (!line || *line == '\0')
{
ft_free_strs(&keep, &line, &tmp);
return (NULL);
}
return (line);
}