-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
107 lines (96 loc) · 2.43 KB
/
get_next_line_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rel-fagr <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/27 13:27:53 by rel-fagr #+# #+# */
/* Updated: 2021/11/27 18:47:17 by rel-fagr ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
static char *ft_creat_str(void)
{
char *str;
str = (char *)malloc(sizeof(char));
if (!str)
return (NULL);
ft_bzero(str, 1);
return (str);
}
static int ft_strchr2(char *s, char c)
{
int i;
i = 0;
while (s[i])
{
if (s[i] == c)
return (0);
i++;
}
return (1);
}
static unsigned int len(char *str)
{
unsigned int i;
i = 0;
while (str[i] != '\n' && str[i])
i++;
if (ft_strlen(str) == i)
return (ft_strlen(str) - 1);
return (i);
}
static char *ft_read_buf(char *str, int *fd, char *ptr)
{
int count_octe;
char *buf;
count_octe = 1;
buf = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buf)
return (NULL);
ft_bzero(buf, (BUFFER_SIZE + 1));
while (ft_strchr2(str, '\n'))
{
count_octe = read(*fd, buf, BUFFER_SIZE);
if (count_octe <= 0)
{
if (*str)
break ;
return (free(buf), free(str), NULL);
}
ptr = str;
str = ft_strjoin(str, buf);
if (!str)
return (NULL);
free (ptr);
ft_bzero(buf, BUFFER_SIZE);
}
return (free(buf), str);
}
char *get_next_line(int fd)
{
char *str;
static char *stc[1024];
char *fin_tab;
char *ptr;
if (BUFFER_SIZE <= 0 || fd < 0)
return (0);
ptr = NULL;
str = ft_creat_str();
if (stc[fd])
{
ptr = str;
str = ft_strjoin(stc[fd], str);
free(stc[fd]);
free(ptr);
stc[fd] = NULL;
}
str = ft_read_buf(str, &fd, ptr);
if (!str)
return (NULL);
fin_tab = ft_substr(str, 0, len(str) + 1);
if (ft_strlen(fin_tab) != ft_strlen(str))
stc[fd] = ft_substr(str, len(str) + 1, ft_strlen(str + len(str) + 1));
return (free (str), fin_tab);
}