-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
113 lines (102 loc) · 2.49 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: kawish <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/12/19 16:20:18 by kawish #+# #+# */
/* Updated: 2021/10/12 12:23:35 by kgajadie ######## odam.nl */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static void *ft_memset(void *b, int c, size_t len)
{
size_t i;
unsigned char *new_ptr;
i = 0;
new_ptr = b;
while (i < len)
{
new_ptr[i] = (unsigned char)c;
i++;
}
return (b);
}
static char *ft_strchr(const char *s, int c)
{
int i;
i = 0;
while (s[i] != (char)c)
{
if (s[i] == '\0')
{
return (0);
}
i++;
}
return (((char *)&(s[i])));
}
static char *c_ft_strjoin(char const *s1, char const *s2)
{
size_t clen;
char *ret;
if (!s1 && !s2)
return (NULL);
else if (!s1)
{
free((char *)s1);
return (c_ft_strdup(s2));
}
else if (!s2)
{
free((char *)s1);
return (c_ft_strdup(s1));
}
clen = ft_strlen(s1) + ft_strlen(s2);
ret = malloc(clen + 1);
if (!ret)
return (NULL);
ft_strlcpy(ret, s1, clen + 1);
ft_strlcat(ret, s2, clen + 1);
free((char *)s1);
return (ret);
}
static int helper(int fd, char *buff, char **line)
{
int n;
char *ptr_a;
n = 1;
while (n)
{
if (*buff == '\0')
{
n = read(fd, buff, BUFFER_SIZE);
if (n < 0)
return (-1);
buff[n] = '\0';
}
if (ft_strchr(buff, '\n'))
{
ptr_a = ft_strchr(buff, '\n');
*ptr_a++ = '\0';
*line = c_ft_strjoin(*line, buff);
ft_memmove(buff, ptr_a, (ft_strlen(ptr_a) + 1));
return (1);
}
*line = c_ft_strjoin(*line, buff);
ft_memset(buff, '\0', ft_strlen(buff) + 1);
}
return (0);
}
int get_next_line(int fd, char **line)
{
static char buff[BUFFER_SIZE + 1];
if (BUFFER_SIZE <= 0 || fd < 0 || line == NULL)
return (-1);
*line = malloc(1 * sizeof(*(*line)));
if (*line == NULL)
return (-1);
ft_memset(*line, '\0', 1 * sizeof(*(*line)));
return (helper(fd, buff, line));
}