-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
104 lines (95 loc) · 2.16 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agoksu <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/31 12:16:59 by agoksu #+# #+# */
/* Updated: 2023/05/31 12:17:01 by agoksu ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_trim(char *rd)
{
int i;
char *rt;
int len;
int j;
j = 0;
i = 0;
len = 0;
while (rd[i] && rd[i] != '\n')
i++;
if (rd[i] == '\n')
i++;
len = ft_strlen(rd + i);
rt = (char *)malloc(sizeof(char) * (len + 1));
while (rd[i])
rt[j++] = rd[i++];
rt[j] = 0;
free (rd);
return (rt);
}
char *ft_line(char *rt, char *rd)
{
int i;
i = 0;
if (!rd)
return (NULL);
while (rd[i] && rd[i] != '\n')
i++;
if (rd[i] == '\n')
i++;
rt = (char *)malloc(sizeof(char) * (i + 1));
i = 0;
while (rd[i] && rd[i] != '\n')
{
rt[i] = rd[i];
i++;
}
if (rd[i] == '\n')
rt[i++] = '\n';
rt[i] = 0;
return (rt);
}
char *ft_read(int fd, char *rt)
{
char *rd;
int count;
count = 1;
rd = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
while (count > 0)
{
count = read(fd, rd, BUFFER_SIZE);
if (count == -1)
{
free(rd);
return (NULL);
}
rd[count] = 0;
rt = ft_strjoin(rt, rd);
if (ft_strchr(rt, '\n'))
break ;
}
free (rd);
return (rt);
}
char *get_next_line(int fd)
{
static char *rd;
char *line;
line = NULL;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
rd = ft_read(fd, rd);
if (!rd || ft_strlen(rd) < 1)
{
free(rd);
rd = NULL;
return (NULL);
}
line = ft_line(line, rd);
rd = ft_trim(rd);
return (line);
}