-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
90 lines (82 loc) · 2.29 KB
/
Copy pathget_next_line.c
File metadata and controls
90 lines (82 loc) · 2.29 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: asuc <asuc@student.42angouleme.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/08 19:51:27 by asuc #+# #+# */
/* Updated: 2023/11/09 00:49:29 by asuc ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void free_null(char **ptr)
{
if (ptr && *ptr)
{
free(*ptr);
*ptr = NULL;
}
}
static char *join_line(char **buffer, ssize_t nl_index)
{
char *line;
char *new_buffer;
if (nl_index >= 0)
{
line = ft_substr(*buffer, 0, nl_index + 1);
if ((*buffer)[nl_index + 1] == '\0')
new_buffer = NULL;
else
new_buffer = ft_strdup(*buffer + nl_index + 1);
free_null(buffer);
*buffer = new_buffer;
}
else
{
if (!(*buffer)[0])
{
free_null(buffer);
return (NULL);
}
line = ft_strdup(*buffer);
free_null(buffer);
}
return (line);
}
static char *read_line(int fd, char **buffer)
{
char *read_buffer;
ssize_t bytes_read;
char *temp;
char *nl_ptr;
read_buffer = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (read_buffer == NULL)
return (NULL);
nl_ptr = ft_strchr(*buffer, '\n');
while (!nl_ptr)
{
bytes_read = read(fd, read_buffer, BUFFER_SIZE);
if (bytes_read <= 0)
{
free(read_buffer);
return (join_line(buffer, -1));
}
read_buffer[bytes_read] = '\0';
temp = ft_strjoin(*buffer, read_buffer);
free_null(buffer);
*buffer = temp;
nl_ptr = ft_strchr(*buffer, '\n');
}
free(read_buffer);
return (join_line(buffer, nl_ptr - *buffer));
}
char *get_next_line(int fd)
{
static char *buffer[OPEN_MAX];
if (fd < 0 || BUFFER_SIZE <= 0 || fd > OPEN_MAX)
return (NULL);
if (!buffer[fd])
buffer[fd] = ft_strdup("");
return (read_line(fd, &buffer[fd]));
}