-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
112 lines (101 loc) · 2.51 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ialdidi <ialdidi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/06 15:07:44 by ialdidi #+# #+# */
/* Updated: 2023/12/06 15:07:45 by ialdidi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
void update_line(char **str)
{
char *tmp;
tmp = *str;
while (*tmp && *tmp != '\n')
tmp++;
if (*tmp == '\n' && *(tmp + 1))
{
tmp = ft_strdup(++tmp);
if (!tmp)
return (free(*str), (void)(*str = NULL));
}
else
tmp = NULL;
free(*str);
*str = tmp;
}
char *create_line(char *str)
{
char *extracted_line;
int i;
i = 0;
while (str[i] && str[i] != '\n')
i++;
i = i + 1 * (str[i] == '\n');
extracted_line = (char *)malloc(i + 1);
if (!extracted_line)
return (free(str), str = NULL);
i = 0;
while (str[i])
{
extracted_line[i] = str[i];
if (str[i++] == '\n')
break ;
}
extracted_line[i] = '\0';
return (extracted_line);
}
void insert_line(char **str, char *buffer)
{
char *tmp;
tmp = ft_strdup(*str);
if (!tmp)
return (free(*str), (void)(*str = NULL));
free(*str);
*str = ft_strjoin(tmp, buffer);
free(tmp);
}
void read_line(int fd, char **str)
{
char *buffer;
char *nl;
int rd;
nl = NULL;
buffer = malloc((size_t)BUFFER_SIZE + 1);
if (!buffer)
return (free(*str), (void)(*str = NULL));
while (!nl)
{
rd = read(fd, buffer, BUFFER_SIZE);
if (rd <= 0)
{
free(buffer);
buffer = NULL;
return ;
}
buffer[rd] = '\0';
nl = ft_strchr(buffer, '\n');
insert_line(str, buffer);
}
free(buffer);
}
char *get_next_line(int fd)
{
static char *str = NULL;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0
|| BUFFER_SIZE > 2147483647 || read(fd, NULL, 0) < 0)
return (free(str), str = NULL);
if (!str || !ft_strchr(str, '\n'))
read_line(fd, &str);
if (!str)
return (NULL);
line = create_line(str);
if (!line)
return (str = NULL);
update_line(&str);
return (line);
}