-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
126 lines (113 loc) · 2.71 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
115
116
117
118
119
120
121
122
123
124
125
126
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jvalle-d <jvalle-d@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/06/11 12:40:06 by jvalle-d #+# #+# */
/* Updated: 2024/06/12 13:33:26 by jvalle-d ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_joinfree(char *buffer, char *aux)
{
char *temp;
temp = ft_strjoin(buffer, aux);
free(buffer);
return (temp);
}
char *ft_readbuffer(char *buffer, int fd)
{
int i;
char *aux;
if (!buffer)
{
buffer = ft_calloc(1, 1);
if (!buffer)
return (NULL);
}
aux = ft_calloc(BUFFER_SIZE + 1, 1);
i = 1;
while ((!ft_strchr(aux, '\n')) && i > 0)
{
i = read(fd, aux, BUFFER_SIZE);
if (i == -1)
return (free(aux), NULL);
aux[i] = '\0';
buffer = ft_joinfree(buffer, aux);
if (!buffer)
return (NULL);
}
free(aux);
return (buffer);
}
char *ft_readline(char *buffer)
{
char *line;
int i;
i = 0;
if (!buffer[i])
return (NULL);
while (buffer[i] != '\0' && buffer[i] != '\n')
i++;
line = ft_calloc(i + 1 + (buffer[i] == '\n'), 1);
if (!line)
return (NULL);
i = 0;
while (buffer[i] != '\n' && buffer[i])
{
line[i] = buffer[i];
i++;
}
if (buffer[i] == '\n')
line[i] = '\n';
return (line);
}
char *ft_updatebuffer(char *buffer)
{
int i;
int j;
char *update;
i = 0;
while (buffer[i] && buffer[i] != '\n')
i++;
if (!buffer[i])
return (ft_free(buffer));
update = ft_calloc((ft_strlen(buffer) - i + 1), 1);
if (!update)
return (ft_free(buffer));
i++;
j = 0;
while (buffer[i])
update[j++] = buffer[i++];
free(buffer);
return (update);
}
char *get_next_line(int fd)
{
static char *buffer;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
buffer = ft_readbuffer(buffer, fd);
if (!buffer)
return (ft_free(buffer));
line = ft_readline(buffer);
buffer = ft_updatebuffer(buffer);
return (line);
}
#include <stdio.h>
int main ()
{
int fd;
char *print;
fd = open("archivo.txt", O_RDONLY);
while ((print = get_next_line(fd)) != NULL)
{
printf("\033[35m Mi Linea en Amarillo:%s\n",print);
free (print);
}
close (fd);
return (0);
}