-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line_bonus.c
More file actions
113 lines (104 loc) · 2.46 KB
/
get_next_line_bonus.c
File metadata and controls
113 lines (104 loc) · 2.46 KB
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_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ommohame <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/05 17:24:27 by ommohame #+# #+# */
/* Updated: 2022/03/12 14:54:35 by ommohame ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *realloc_str(char *str, char *line)
{
size_t i;
size_t j;
char *tmp;
i = 0;
while (str[i] && str[i] == line[i])
i++;
if (!str[i])
{
free(str);
return (NULL);
}
tmp = (char *)malloc(sizeof(char) * (ft_strlen(str) - i + 1));
if (!tmp)
return (NULL);
j = 0;
while (str[i])
{
tmp[j] = str[i];
i++;
j++;
}
tmp[j] = 0;
free (str);
return (tmp);
}
char *linooo(char *str)
{
size_t i;
char *line;
i = 0;
if (!str[i])
return (NULL);
while (str[i] && str[i] != '\n')
i++;
if (str[i] == '\n')
line = (char *)malloc(sizeof(char) * (i + 2));
else
line = (char *)malloc(sizeof(char) * (i + 1));
if (!line)
return (NULL);
i = -1;
while (str[++i] && str[i] != '\n')
line[i] = str[i];
if (str[i] == '\n')
line[i++] = '\n';
line[i] = 0;
return (line);
}
char *reading(char *str, char *bfr, int fd)
{
int ret;
ret = read(fd, bfr, BUFFER_SIZE);
if (ret == -1)
{
free (bfr);
return (NULL);
}
bfr[ret] = 0;
str = ft_strjoin(str, bfr);
while (ret != 0 && !ft_strchr(str, '\n'))
{
ret = read(fd, bfr, BUFFER_SIZE);
if (ret == -1)
{
free (bfr);
return (NULL);
}
bfr[ret] = 0;
str = ft_strjoin(str, bfr);
}
free(bfr);
return (str);
}
char *get_next_line(int fd)
{
char *bfr;
static char *str[1024];
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
bfr = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!bfr)
return (NULL);
str[fd] = reading(str[fd], bfr, fd);
if (!str[fd])
return (NULL);
line = linooo(str[fd]);
str[fd] = realloc_str(str[fd], line);
return (line);
}