-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
119 lines (110 loc) · 2.64 KB
/
get_next_line.c
File metadata and controls
119 lines (110 loc) · 2.64 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slargo-b <slargo-b@student.42madrid.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/02/10 16:14:17 by slargo-b #+# #+# */
/* Updated: 2025/02/12 11:18:51 by slargo-b ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *update_save(char *save)
{
char *new_save;
int i;
int j;
i = 0;
while (save && save[i] && save[i] != '\n')
i++;
if (save && !save[i])
return (free(save), NULL);
new_save = malloc(ft_strlen(save) - i + 1);
if (!new_save)
return (NULL);
i++;
j = 0;
while (save && save[i])
new_save[j++] = save[i++];
new_save[j] = '\0';
return (free(save), new_save);
}
static char *get_line(char *save)
{
char *line;
int i;
i = 0;
if (!save)
return (NULL);
while (save[i] && save[i] != '\n')
i++;
if (save[i] == '\n')
i++;
line = malloc((i + 1) * sizeof(char));
if (!line)
return (NULL);
i = 0;
while (save[i] && save[i] != '\n')
{
line[i] = save[i];
i++;
}
if (save[i] == '\n')
line[i++] = '\n';
line[i] = '\0';
return (line);
}
static char *read_and_save(int fd, char *save)
{
char *buffer;
int read_a;
read_a = 1;
buffer = malloc(BUFFER_SIZE + 1);
if (!buffer)
return (NULL);
while (read_a > 0)
{
read_a = read(fd, buffer, BUFFER_SIZE);
if (read_a <= 0)
break ;
buffer[read_a] = '\0';
save = ft_strjoin_gnl(save, buffer);
if (!save)
return (free(buffer), NULL);
if (has_newline(save))
break ;
}
return (free(buffer), save);
}
char *get_next_line(int fd)
{
char *line;
static char *save;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
save = read_and_save(fd, save);
if (!save)
return (NULL);
line = get_line(save);
if (!line)
return (free(save), NULL);
save = update_save(save);
if (!save && !line[0])
return (free(line), NULL);
return (line);
}
/* int main(int argc, char *argv[])
{
char *str;
int fd;
(void)argc;
(void)argv;
fd = open("prueba.txt", O_RDONLY);
while ((str = get_next_line(fd)) != NULL)
{
printf("%s", str);
free (str);
}
close(fd);
} */