-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
109 lines (99 loc) · 2.52 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: fhideous <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/02 17:25:55 by fhideous #+# #+# */
/* Updated: 2020/12/02 17:25:57 by fhideous ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int find_transl(const char *str)
{
int i;
if (!str)
return (-1);
i = 0;
while (*(str + i) != '\0')
{
if (*(str + i) == '\n')
return (i);
i++;
}
return (-1);
}
int add_line(char **line, char **donor, int n)
{
char *tmp;
char *new_rmd;
int i;
if (n < 0)
return (0);
if (!(tmp = ft_calloc(n + 1, sizeof(char))))
return (-1);
i = -1;
while (++i < n)
tmp[i] = *((*donor) + i);
*line = tmp;
if (!*donor)
return (1);
if (!(new_rmd = ft_substr(*donor, n + 1, ft_strlen(*donor) - n - 1)))
return (-1);
free(*donor);
*donor = new_rmd;
return (1);
}
static int read_buf(int fd, char **rmd)
{
int count;
char *buf_rd;
char *joined;
if (!(buf_rd = ft_calloc(BUFFER_SIZE + 1, sizeof(char))))
return (-1);
if ((count = read(fd, buf_rd, BUFFER_SIZE)) <= 0)
free(buf_rd);
if (count < 0)
return (-1);
else if (count == 0)
return (0);
if (!(joined = ft_strjoin(*rmd, buf_rd)))
return (-1);
free(buf_rd);
free(*rmd);
*rmd = joined;
return (1);
}
static void ft_free(char **str)
{
free(*str);
*str = NULL;
}
int get_next_line(int fd, char **line)
{
static char *rem;
int is_tr;
int count;
static int is_first;
count = 1;
if (!line || BUFFER_SIZE <= 0)
return (-1);
while (count != 0)
{
if ((is_tr = add_line(&*line, &rem, find_transl(rem))) == -1)
return (-1);
if (is_tr == 1)
return (1);
if ((count = read_buf(fd, &rem)) == -1)
return (-1);
}
if (!is_first)
*line = "\0";
if (!*line && (!rem || !*rem) && is_first++)
return (0);
if ((add_line(&*line, &rem, ft_strlen(rem))) == -1)
return (-1);
ft_free(&rem);
return (0);
}