-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
109 lines (100 loc) · 2.52 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
97
98
99
100
101
102
103
104
105
106
107
108
109
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aelkheta <aelkheta@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/01 18:21:05 by aelkheta #+# #+# */
/* Updated: 2023/12/08 17:14:14 by aelkheta ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_the_rest(char *buffer)
{
int i;
int j;
char *str;
i = 0;
while (buffer[i] && buffer[i] != '\n')
i++;
if (!buffer[i])
return (ft_free(buffer));
str = (char *)malloc(sizeof(char) * (ft_strlen(buffer) - i + 1));
if (!str)
return (ft_free(buffer));
i++;
j = 0;
while (buffer[i])
str[j++] = buffer[i++];
str[j] = '\0';
free(buffer);
return (str);
}
char *check_next_line(char *buffer)
{
int i;
int len;
char *i_am_the_line;
i = 0;
len = 0;
if (!buffer)
return (NULL);
while (buffer[len] && buffer[len] != '\n')
len++;
i_am_the_line = (char *)malloc(sizeof(char) * len + 2);
if (!i_am_the_line)
return (NULL);
while (buffer[i] && buffer[i] != '\n')
{
i_am_the_line[i] = buffer[i];
i++;
}
if (buffer[i] == '\n')
i_am_the_line[i++] = '\n';
i_am_the_line[i] = '\0';
return (i_am_the_line);
}
char *reach_the_line(int fd, char *buffer)
{
char *line;
int bytes_read;
line = malloc(sizeof(char) * BUFFER_SIZE + 1);
if (!line)
return (NULL);
bytes_read = 1;
while (bytes_read > 0 && !ft_strchr(buffer, '\n'))
{
bytes_read = read(fd, line, BUFFER_SIZE);
if (bytes_read < 0)
{
free(line);
free(buffer);
return (NULL);
}
line[bytes_read] = '\0';
buffer = ft_strjoin(buffer, line);
if (!buffer)
return (NULL);
}
free(line);
return (buffer);
}
char *get_next_line(int fd)
{
char *line;
static char *buffer;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buffer = reach_the_line(fd, buffer);
if (!buffer)
return (NULL);
line = check_next_line(buffer);
buffer = get_the_rest(buffer);
if (line[0] == '\0')
{
free(line);
return (NULL);
}
return (line);
}