-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
75 lines (68 loc) · 2.26 KB
/
get_next_line_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anhigo-s <anhigo-s@student.42sp.org.br +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/28 00:35:44 by anhigo-s #+# #+# */
/* Updated: 2021/10/10 00:15:14 by anhigo-s ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static char *get_line(char **buffer_backup, size_t i)
{
char *line;
char *temp;
while (((*buffer_backup)[i] != '\n') && ((*buffer_backup)[i] != '\0'))
i++;
if ((*buffer_backup)[i] == 0)
{
line = gnl_strdup(*buffer_backup);
free(*buffer_backup);
*buffer_backup = NULL;
}
else
{
line = gnl_substr(*buffer_backup, 0, i + 1);
temp = gnl_strdup(&(*buffer_backup)[i + 1]);
free(*buffer_backup);
*buffer_backup = NULL;
if (*temp)
*buffer_backup = gnl_strdup(temp);
free(temp);
temp = NULL;
}
return (line);
}
static char *get_next(int fd, ssize_t bytes_read, char *temp_buff)
{
static char *s_buffer[256];
char *temp;
while (bytes_read > 0)
{
temp_buff[bytes_read] = '\0';
if (s_buffer[fd] == 0)
s_buffer[fd] = gnl_strdup("");
temp = gnl_strdup(s_buffer[fd]);
free(s_buffer[fd]);
s_buffer[fd] = gnl_strjoinfree(temp, temp_buff);
if (gnl_strchr(s_buffer[fd], '\n'))
break ;
bytes_read = read(fd, temp_buff, BUFFER_SIZE);
}
if (bytes_read == 0 && s_buffer[fd] == 0)
return (NULL);
return (get_line(&s_buffer[fd], 0));
}
char *get_next_line(int fd)
{
char temp_buff[BUFFER_SIZE + 1];
ssize_t bytes_read;
if ((fd < 0) || (BUFFER_SIZE < 1) || (read(fd, temp_buff, 0) < 0))
return (NULL);
bytes_read = read(fd, temp_buff, BUFFER_SIZE);
if (bytes_read < 0)
return (NULL);
return (get_next(fd, bytes_read, temp_buff));
}