-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
94 lines (86 loc) · 2.35 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aldokezer <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/06 11:08:06 by orezek #+# #+# */
/* Updated: 2023/11/08 20:56:34 by aldokezer ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int initialize_buffer(int fd, char **buf)
{
int bytes_read;
*buf = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!*buf)
return (-1);
bytes_read = read(fd, *buf, BUFFER_SIZE);
if (bytes_read <= 0)
{
free(*buf);
*buf = NULL;
return (-1);
}
(*buf)[bytes_read] = '\0';
return (0);
}
int ft_has_newline(char *str)
{
while (*str)
{
if (*str == '\n')
return (1);
str++;
}
return (0);
}
char *ft_strjoin(char *s1, char *s2)
{
char *new_str;
int i;
int j;
i = 0;
j = 0;
new_str = malloc(sizeof(char) * (ft_strlen(s1) + ft_strlen(s2) + 1));
if (!new_str)
return (NULL);
if (s1)
{
while (s1[i])
new_str[j++] = s1[i++];
}
i = 0;
while (s2[i])
new_str[j++] = s2[i++];
new_str[j] = '\0';
free(s1);
return (new_str);
}
char *get_next_line(int fd)
{
static char *buf;
char *new_line;
char *temp;
int bytes_read;
new_line = NULL;
if (buf == NULL && initialize_buffer(fd, &buf) == -1)
return (NULL);
if (!ft_has_newline(buf))
{
while (!ft_has_newline(buf))
{
new_line = ft_strjoin(new_line, buf);
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read <= 0 && new_line[0] == '\0')
return (free(buf), free(new_line), buf = NULL);
if (bytes_read <= 0)
return (free(buf), buf = NULL, new_line);
buf[bytes_read] = '\0';
}
temp = ft_extract_line_and_movebytes(buf);
return (new_line = ft_strjoin(new_line, temp), free(temp), new_line);
}
return (new_line = ft_extract_line_and_movebytes(buf));
}