-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
114 lines (103 loc) · 2.45 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
114
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: buthor <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/11 12:00:00 by buthor #+# #+# */
/* Updated: 2021/01/06 20:54:01 by buthor ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_strdup(const char *s1)
{
char *dst;
size_t len;
size_t i;
len = ft_strlen(s1);
i = 0;
dst = NULL;
if ((dst = (char *)malloc(sizeof(char) * (len + 1))) == NULL)
return (NULL);
while (i < len)
{
dst[i] = s1[i];
i++;
}
dst[i] = '\0';
return (dst);
}
char *ft_strchr(const char *s, int c)
{
char *src;
src = (char *)s;
while (*src != '\0')
{
if (*src == (char)c)
return (src);
src++;
}
if (*src == (char)c && (char)c == '\0')
return (src);
return (NULL);
}
void ft_strcpy(char *dst, const char *s)
{
int i;
i = 0;
while (s[i] != '\0')
{
dst[i] = s[i];
i++;
}
dst[i] = '\0';
}
char *ft_check(char **tail, char **line)
{
char *pn;
pn = NULL;
if (*tail)
{
if ((pn = ft_strchr(*tail, '\n')))
{
*pn = '\0';
*line = ft_strdup(*tail);
ft_strcpy(*tail, ++pn);
}
else
{
*line = ft_strdup(*tail);
ft_bzero(*tail, ft_strlen(*tail));
}
}
else
*line = ft_calloc(1, 1);
return (pn);
}
int get_next_line(int fd, char **line)
{
char buff[BUFFER_SIZE + 1];
static int bwr;
char *pn;
static char *tail;
if (!line || fd < 0 || BUFFER_SIZE <= 0 || (read(fd, 0, 0) < 0))
return (-1);
pn = ft_check(&tail, line);
while (!pn && (bwr = read(fd, buff, BUFFER_SIZE)))
{
if (bwr < 0 || *line == NULL)
break ;
buff[bwr] = '\0';
if ((norm25(&pn, buff, &tail, line)) == -1)
return (-1);
}
if ((bwr == 0 && tail) || (*line == NULL && tail))
{
free(tail);
tail = NULL;
}
if (*line == NULL || bwr < 0)
return (-1);
return ((bwr == 0 && (tail == NULL || ft_strlen(tail) == 0)) ? 0 : 1);
}