-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
106 lines (97 loc) · 2.32 KB
/
get_next_line.c
File metadata and controls
106 lines (97 loc) · 2.32 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: manufern <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/20 18:42:50 by manufern #+# #+# */
/* Updated: 2023/10/26 13:39:58 by manufern ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *next_line(char *buffer)
{
char *tmp;
tmp = ft_strchr(buffer, '\n') + 1;
if (ft_strlen(tmp) > 0)
{
tmp = ft_strdup(tmp);
}
else
{
tmp = NULL;
}
if (buffer != NULL)
{
free(buffer);
}
return (tmp);
}
int ft_found_line(char *buffer)
{
int i;
i = 0;
while (buffer[i] != '\0')
{
if (buffer[i] == '\n')
return (1);
i++;
}
if (i > 0)
return (2);
return (0);
}
char *ft_read(int fd, char *buffer, int *bytes_read)
{
char frag[BUFFER_SIZE + 1];
char *tmp;
if (read(fd, 0, 0) < 0)
{
free (buffer);
return (NULL);
}
*bytes_read = read(fd, frag, BUFFER_SIZE);
if (*bytes_read > 0)
frag[*bytes_read] = '\0';
if (*bytes_read <= 0)
{
if (buffer)
return (buffer);
return (NULL);
}
if (!buffer)
tmp = ft_strdup(frag);
else
{
tmp = ft_strjoin(buffer, frag);
free(buffer);
}
return (tmp);
}
char *get_next_line(int fd)
{
static char *buffer = NULL;
char *line;
int has_line;
int bytes_read;
if (fd < 0 || BUFFER_SIZE <= 0)
return (line = NULL);
buffer = ft_read(fd, buffer, &bytes_read);
if (buffer == NULL)
return (NULL);
has_line = ft_found_line(buffer);
if (has_line == 1)
{
line = ft_substr(buffer);
if (!line)
return (free(buffer), buffer = NULL, NULL);
return (buffer = next_line(buffer), line);
}
if (has_line == 2 && bytes_read < BUFFER_SIZE)
{
line = ft_strdup(buffer);
return (free(buffer), buffer = NULL, line);
}
return (get_next_line(fd));
}