-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
96 lines (87 loc) · 2.37 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tairribe <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/22 18:20:46 by tairan #+# #+# */
/* Updated: 2022/11/20 13:20:04 by tairribe ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t read_buffer(char **buffer, size_t size, int fd)
{
int read_size;
char *b;
*buffer = malloc((size + 1) * sizeof(char));
if (!*buffer)
return (0);
read_size = read(fd, *buffer, size);
if (read_size <= 0)
{
free(*buffer);
buffer[0] = NULL;
return (0);
}
b = *buffer;
b[read_size] = '\0';
return (read_size);
}
static char *get_text(char **buffer)
{
char *line;
size_t len;
size_t n;
char *tmp;
tmp = NULL;
len = ft_strlen(*buffer);
if (!ft_strchr(*buffer, '\n'))
n = len;
else
n = (ft_strchr(*buffer, '\n') - *buffer) + 1;
line = malloc((n + 1) * sizeof(char));
if (!line)
return (NULL);
ft_strlcpy(line, *buffer, n + 1);
if (n != len)
{
tmp = malloc((len - n + 1) * sizeof(char));
ft_strlcpy(tmp, &(*buffer)[n], len - n + 1);
}
free(*buffer);
buffer[0] = tmp;
tmp = NULL;
return (line);
}
static char *join(char *line, char *text)
{
char *tmp;
if (!line)
return (text);
tmp = ft_strjoin(line, text);
free(line);
free(text);
return (tmp);
}
char *get_next_line(int fd)
{
static char *buffer[1024];
size_t read_size;
char *line;
if (BUFFER_SIZE < 1 || fd < 0 || fd > 1023)
return (NULL);
line = NULL;
read_size = 0;
if (!buffer[fd])
read_size = read_buffer(&buffer[fd], BUFFER_SIZE, fd);
while (read_size || buffer[fd])
{
line = join(line, get_text(&buffer[fd]));
if (line[ft_strlen(line) - 1] == '\n')
return (line);
if (!buffer[fd])
read_size = read_buffer(&buffer[fd], BUFFER_SIZE, fd);
}
return (line);
}