-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
83 lines (75 loc) · 2.01 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ytaya <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/17 15:04:24 by ytaya #+# #+# */
/* Updated: 2021/11/19 00:10:26 by ytaya ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
void ft_free(char **str)
{
free(*str);
*str = NULL;
}
void ft_get_line(char **rest, char **line)
{
int i;
char *temp;
i = 0;
while ((*rest)[i] != '\n' && (*rest)[i] != '\0')
i++;
if ((*rest)[i] == '\n')
{
*line = ft_substr(*rest, 0, ++i);
temp = *rest;
*rest = ft_strdup(*rest + i);
ft_free(&temp);
}
else
{
*line = ft_strdup(*rest);
ft_free(rest);
}
if ((*line)[0] == '\0')
ft_free(line);
}
void ft_read(int fd, char **rest, char **line, char **buffer)
{
ssize_t r;
char *temp;
r = 1;
while (r && !ft_strchr(*rest, '\n'))
{
r = read(fd, *buffer, BUFFER_SIZE);
(*buffer)[r] = '\0';
temp = *rest;
*rest = ft_strjoin(temp, *buffer);
ft_free(&temp);
}
ft_free(buffer);
ft_get_line(rest, line);
}
char *get_next_line(int fd)
{
static char *rest;
char *line;
char *buffer;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buffer = (char *)malloc(sizeof(*buffer) * (BUFFER_SIZE + 1));
if (!buffer)
return (NULL);
if (read(fd, buffer, 0) < 0)
{
ft_free(&buffer);
return (NULL);
}
if (!rest)
rest = ft_strdup("");
ft_read(fd, &rest, &line, &buffer);
return (line);
}