-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
114 lines (103 loc) · 2.46 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: javiersa <javiersa@student.42malaga.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/10 17:46:54 by javiersa #+# #+# */
/* Updated: 2023/01/19 20:34:12 by javiersa ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_freeandjoin_gnl(char *buffer, char *aux)
{
char *strjoin;
strjoin = ft_strjoin_gnl(buffer, aux);
free(buffer);
buffer = NULL;
return (strjoin);
}
char *ft_next(char *buffer)
{
int i;
int j;
char *line;
i = 0;
while (buffer[i])
{
if (buffer[i] == '\n')
{
line = ft_calloc_gnl((ft_strlen_gnl(&buffer[i])), sizeof(char));
i++;
j = 0;
while (buffer[i])
line[j++] = buffer[i++];
free(buffer);
buffer = 0;
return (line);
}
i++;
}
free(buffer);
buffer = NULL;
return (NULL);
}
char *ft_line(char *buffer)
{
char *line;
int i;
i = 0;
while (buffer[i] && buffer[i] != '\n')
i++;
if (buffer[i] == '\n')
{
line = ft_calloc_gnl(i + 2, sizeof(char));
line[i] = '\n';
}
else
line = ft_calloc_gnl(i + 1, sizeof(char));
while (--i >= 0)
line[i] = buffer[i];
if (ft_strlen_gnl(line) == 0)
return (free(line), NULL);
return (line);
}
char *read_file(int fd, char *buffer)
{
char *aux;
int i;
if (!buffer)
buffer = ft_calloc_gnl(1, 1);
aux = ft_calloc_gnl(BUFFER_SIZE + 1, sizeof(char));
i = 1;
while (i > 0)
{
i = read(fd, aux, BUFFER_SIZE);
if (i != BUFFER_SIZE)
aux[i] = 0;
buffer = ft_freeandjoin_gnl(buffer, aux);
if (ft_strchr_gnl(aux, '\n'))
break ;
}
free(aux);
aux = NULL;
return (buffer);
}
char *get_next_line(int fd)
{
static char *buffer;
char *line;
if (read(fd, 0, 0) < 0)
{
free(buffer);
buffer = NULL;
return (NULL);
}
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buffer = read_file(fd, buffer);
line = ft_line(buffer);
buffer = ft_next(buffer);
return (line);
}