-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
113 lines (102 loc) · 2.25 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
110
111
112
113
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mpeulet <mpeulet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/02 15:32:54 by mpeulet #+# #+# */
/* Updated: 2023/10/02 15:42:06 by mpeulet ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
size_t ft_strlen(const char *s)
{
size_t i;
i = 0;
if (!s)
return (0);
while (s[i])
i++;
return (i);
}
int strchr_gnl(char *s, char x)
{
int i;
i = 0;
if (!s)
return (0);
while (s[i])
{
if (s[i] == x)
return (1);
i++;
}
return (0);
}
char *ft_join_gnl(char *s1, char *s2)
{
int i;
int j;
char *join;
if (!s1)
{
s1 = malloc(sizeof(char) * 1);
s1[0] = 0;
}
join = malloc(ft_strlen(s1) + ft_strlen(s2) + 1);
if (!join)
return (free(s1), NULL);
i = -1;
j = -1;
while (s1[++i])
join[i] = s1[i];
while (s2[++j])
join[i + j] = s2[j];
join[i + j] = 0;
free(s1);
return (join);
}
void clean_gnl(char *line, char *buffer)
{
int i;
int j;
i = 0;
j = 0;
while (line[i] && line[i] != 10)
i++;
if (line[i] == 10)
i++;
while (line[i])
{
buffer[j] = line[i];
line[i] = 0;
i++;
j++;
}
buffer[j] = 0;
}
char *get_next_line(int fd)
{
static char buffer[BUFFER_SIZE + 1];
char *line;
int byte_read;
if (fd < 0 || BUFFER_SIZE < 1)
return (NULL);
line = 0;
line = ft_join_gnl(line, buffer);
byte_read = 1;
while (byte_read > 0 && !strchr_gnl(line, 10))
{
byte_read = read(fd, buffer, BUFFER_SIZE);
if (byte_read < 0)
return (free(line), NULL);
buffer[byte_read] = 0;
line = ft_join_gnl(line, buffer);
}
if (!line[0])
return (free(line), NULL);
else
clean_gnl(line, buffer);
return (line);
}