-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
95 lines (85 loc) · 2.4 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vscabell <vscabell@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/12 08:37:34 by vscabell #+# #+# */
/* Updated: 2020/07/29 18:49:13 by vscabell ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static int ft_breakline(char *str, char c)
{
int i;
i = 0;
while (str[i] && str[i] != c)
i++;
if (str[i] == '\0')
return (-1);
return (i);
}
static int ft_newline(char **str, char **line, int i, char *buffer)
{
char *aux;
*line = ft_substr(*str, 0, i);
aux = ft_substr(*str, i + 1, ft_strlen(*str) - i);
free(*str);
*str = aux;
if (*str && *str[0] == '\0')
{
free(*str);
*str = NULL;
}
free(buffer);
buffer = NULL;
return (1);
}
static int ft_endoffile(char **str, char **line, char *buffer)
{
if (*str)
{
*line = ft_strdup(*str);
free(*str);
*str = NULL;
}
else
*line = ft_strdup("");
free(buffer);
buffer = NULL;
return (0);
}
static int ft_gnl(char **line, int fd, char *buffer)
{
static char *str[OPEN_MAX];
char *aux;
int posit;
int ret;
if (str[fd] && (posit = ft_breakline(str[fd], '\n')) != -1)
return (ft_newline(&str[fd], line, posit, buffer));
while ((ret = read(fd, buffer, BUFFER_SIZE)) > 0)
{
buffer[ret] = '\0';
if (!str[fd])
str[fd] = ft_strdup(buffer);
else
{
aux = ft_strjoin(str[fd], buffer);
free(str[fd]);
str[fd] = aux;
}
if ((posit = ft_breakline(str[fd], '\n')) >= 0)
return (ft_newline(&str[fd], line, posit, buffer));
}
return (ft_endoffile(&str[fd], line, buffer));
}
int get_next_line(int fd, char **line)
{
char *buffer;
if (fd < 0 || !line || BUFFER_SIZE < 1 || read(fd, NULL, 0) < 0)
return (-1);
if (!(buffer = malloc((BUFFER_SIZE + 1) * sizeof(char *))))
return (-1);
return (ft_gnl(line, fd, buffer));
}