-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
93 lines (84 loc) · 2.13 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rilliano <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/27 13:47:15 by rilliano #+# #+# */
/* Updated: 2023/05/09 17:14:28 by rilliano ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_next(char *prev, int len)
{
char *n_line;
int i;
if (!prev[len])
{
free(prev);
return (NULL);
}
n_line = ft_calloc((ft_strlen(prev) - len + 1), sizeof(char));
i = 0;
while (prev[len + i])
{
n_line[i] = prev[len + i];
i++;
}
free(prev);
return (n_line);
}
char *ft_line(char *start, int len)
{
char *line;
int i;
line = ft_calloc(len + 1, sizeof(char));
i = 0;
while (i < len)
{
line[i] = start[i];
i++;
}
return (line);
}
char *read_file(int fd, char *start)
{
char *buffer;
int bytes;
buffer = ft_calloc((BUFFER_SIZE + 1), sizeof(char));
while (1)
{
bytes = read(fd, buffer, BUFFER_SIZE);
if (bytes == 0)
break ;
if (bytes == -1)
{
free(buffer);
return (NULL);
}
start = ft_join(start, buffer, bytes);
if (buffer[bytes] == '\n')
break;
}
free(buffer);
return (start);
}
char *get_next_line(int fd)
{
static char *start;
char *line;
int len;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
start = read_file(fd, start);
len = 0;
if (!start || !start[len])
return (NULL);
while (start[len] != '\0' && start[len] != '\n')
len++;
len += (start[len] == '\n');
line = ft_line(start, len);
start = ft_next(start, len);
return (line);
}