-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_next_line.c
130 lines (118 loc) · 2.88 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gkhodizo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/03 15:28:11 by gkhodizo #+# #+# */
/* Updated: 2020/06/14 20:32:42 by gkhodizo ### ########.fr */
/* */
/* ************************************************************************** */
/*
** get_next_line() returns a line read from a text_file descriptor.
** The return value can be 1, 0 or -1 depending on whether a line has been
** read, when the reading has been completed, or if an error has happened.
*/
#include "get_next_line.h"
static char *clean_buff(char *text)
{
size_t i;
size_t llen;
size_t nlen;
char *tmp;
llen = line_len(text);
nlen = buff_len(text) - llen;
if (nlen > 0)
{
if (!(tmp = (char *)malloc((nlen + 1) * sizeof(char))))
return (NULL);
i = 0;
while (text[llen] != '\0')
tmp[i++] = text[++llen];
tmp[i] = '\0';
free(text);
return (tmp);
}
free(text);
text = NULL;
return (text);
}
static int save_to_line(char **line, char *text)
{
size_t len;
if (*line)
{
free(*line);
*line = NULL;
}
len = line_len(text);
if (!(*line = (char *)malloc((len + 1) * sizeof(char))))
return (-1);
(*line)[len] = '\0';
if (text)
{
ft_strncpy(*line, text, len);
if (text[len] == '\n')
return (1);
}
return (0);
}
static char *realloc_append_buff(char *mid, char *tmp)
{
size_t i;
size_t mlen;
size_t tlen;
char *new;
mlen = buff_len(mid);
tlen = buff_len(tmp);
if (!(new = (char *)malloc((mlen + tlen + 1) * sizeof(char))))
return (NULL);
i = 0;
while (i < mlen)
{
new[i] = mid[i];
i++;
}
i = 0;
while (i < tlen)
{
new[mlen] = tmp[i];
i++;
mlen++;
}
new[mlen] = '\0';
return (new);
}
static char *read_append(int fd, char *text, char *tmp)
{
ssize_t bytes_read;
char *mid;
while ((bytes_read = read(fd, tmp, BUFFER_SIZE)) > 0)
{
tmp[bytes_read] = '\0';
mid = text;
text = realloc_append_buff(mid, tmp);
free(mid);
if (is_nl(tmp))
break ;
}
return (text);
}
int get_next_line(int fd, char **line)
{
int ret;
char tmp[BUFFER_SIZE + 1];
static char *text;
if (!line
|| fd < 0 || BUFFER_SIZE <= 0
|| (read(fd, tmp, 0) < 0)
|| !(*line = ft_strdup("")))
return (-1);
text = read_append(fd, text, tmp);
if (text == NULL)
return (0);
ret = save_to_line(line, text);
text = clean_buff(text);
return (ret);
}