-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
109 lines (99 loc) · 2.29 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: moel-asr <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/27 16:26:01 by moel-asr #+# #+# */
/* Updated: 2022/11/01 18:19:25 by moel-asr ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_free(char *s1, char *s2)
{
free(s2);
return (s1);
}
char *ft_read(int fd, char *result)
{
char *str;
int i;
str = malloc(sizeof(char) * BUFFER_SIZE + 1);
i = 1;
while (i > 0)
{
i = read(fd, str, BUFFER_SIZE);
if (i == (-1))
{
free(str);
return (NULL);
}
str[i] = '\0';
result = ft_free(ft_strjoin(result, str), result);
if (ft_strchr(str, '\n'))
break ;
}
free(str);
return (result);
}
char *ft_get_line(char *str)
{
char *line;
int i;
i = 0;
if (str[0] == '\0')
return (NULL);
while (str[i] != '\0' && str[i] != '\n')
i++;
line = malloc(sizeof(char) * i + 2);
i = 0;
while (str[i] != '\0' && str[i] != '\n')
{
line[i] = str[i];
i++;
}
if (str[i] != '\0' && str[i] == '\n')
line[i++] = '\n';
line[i] = '\0';
return (line);
}
char *ft_get_next_line(char *str)
{
char *line;
int i;
int j;
i = 0;
j = 0;
while (str[i] != '\0' && str[i] != '\n')
i++;
if (str[i] == '\0')
{
free(str);
return (NULL);
}
line = malloc(sizeof(char) * (ft_strlen(str) - i + 1));
i++;
while (str[i] != '\0')
{
line[j] = str[i];
i++;
j++;
}
line[j] = '\0';
free(str);
return (line);
}
char *get_next_line(int fd)
{
static char *str;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
str = ft_read(fd, str);
if (!str)
return (NULL);
line = ft_get_line(str);
str = ft_get_next_line(str);
return (line);
}