-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
108 lines (97 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
96
97
98
99
100
101
102
103
104
105
106
107
108
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bhagenlo <[email protected]. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/13 10:09:10 by bhagenlo #+# #+# */
/* Updated: 2022/06/01 11:05:36 by bhagenlo ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *save_join(char *buffer, char *buf)
{
char *tmp;
tmp = gnl_strjoin(buffer, buf);
free(buffer);
return (tmp);
}
char *renew_buffer(char *buffer)
{
int i;
int j;
char *line;
i = 0;
while (buffer[i] && buffer[i] != '\n')
i++;
if (!buffer[i])
{
free(buffer);
return (NULL);
}
line = gnl_calloc((gnl_strlen(buffer) - i + 1), sizeof(char));
i++;
j = 0;
while (buffer[i])
line[j++] = buffer[i++];
free(buffer);
return (line);
}
char *get_line(char *buffer)
{
char *line;
int i;
i = 0;
if (!buffer[i])
return (NULL);
while (buffer[i] && buffer[i] != '\n')
i++;
line = gnl_calloc(i + 2, sizeof(char));
i = 0;
while (buffer[i] && buffer[i] != '\n')
{
line[i] = buffer[i];
i++;
}
if (buffer[i] && buffer[i] == '\n')
line[i++] = '\n';
return (line);
}
char *read_file(int fd, char *res)
{
char *buffer;
int bytes_read;
if (!res)
res = gnl_calloc(1, 1);
buffer = gnl_calloc(BUFFER_SIZE + 1, sizeof(char));
bytes_read = 1;
while (bytes_read > 0)
{
bytes_read = read(fd, buffer, BUFFER_SIZE);
if (bytes_read == -1)
{
free(buffer);
return (NULL);
}
buffer[bytes_read] = 0;
res = save_join(res, buffer);
if (gnl_strchr(buffer, '\n'))
break ;
}
free(buffer);
return (res);
}
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 = read_file(fd, buffer);
if (!buffer)
return (NULL);
line = get_line(buffer);
buffer = renew_buffer(buffer);
return (line);
}