-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
90 lines (82 loc) · 2.38 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gandrade <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/04 01:41:40 by gandrade #+# #+# */
/* Updated: 2021/07/04 14:11:44 by gandrade ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static int return_line(int rd, char **storage, char **line);
static int check_error(int rd, int fd, char *buffer);
static void ft_strclear(char **str);
int get_next_line(int fd, char **line)
{
static char *storage[OPEN_MAX];
char *buffer;
char *aux;
int rd;
buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
rd = read(fd, buffer, BUFFER_SIZE);
check_error(rd, fd, buffer);
while (rd > 0)
{
buffer[rd] = '\0';
if (!storage[fd])
storage[fd] = ft_strdup(buffer);
else
{
aux = ft_strjoin(storage[fd], buffer);
free(storage[fd]);
storage[fd] = aux;
}
if (ft_strchr(storage[fd], '\n'))
break ;
rd = read(fd, buffer, BUFFER_SIZE);
}
free(buffer);
return (return_line(rd, &storage[fd], line));
}
static int return_line(int rd, char **storage, char **line)
{
char *aux;
int i;
if (rd < 0 || !line || BUFFER_SIZE < 1)
return (ERROR);
if (rd == 0 && *storage == 0)
{
*line = ft_strdup("");
ft_strclear(storage);
return (END_OF_FILE);
}
i = 0;
while ((*storage)[i] != '\n' && (*storage)[i] != '\0')
i++;
*line = ft_substr(*storage, 0, i);
if (ft_strchr(*storage, '\n'))
{
aux = ft_strdup(*storage + i + 1);
free(*storage);
*storage = aux;
return (LINE_READ);
}
ft_strclear(storage);
return (END_OF_FILE);
}
static int check_error( int rd, int fd, char *buffer)
{
if (rd < 0 || fd < 0 || !buffer || BUFFER_SIZE < 1)
return (ERROR);
return (0);
}
static void ft_strclear(char **str)
{
if (*str && str)
{
free(*str);
*str = NULL;
}
}