-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
114 lines (105 loc) · 2.3 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
108
109
110
111
112
113
114
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: majjig <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/16 18:16:29 by majjig #+# #+# */
/* Updated: 2021/11/16 18:35:02 by majjig ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *new_remain(char *line, char *remain)
{
int i;
int j;
char *new;
i = 0;
j = 0;
if (is_nl(line) == 0)
{
free(remain);
return (NULL);
}
while (line[j])
{
if (line[j++] == '\n')
break ;
}
if (line[j] == 0)
{
free(remain);
return (0);
}
new = ft_strdup(line + j);
free(remain);
return (new);
}
char *new_line(char *line)
{
int len;
int i;
char *new;
len = 0;
i = 0;
if (is_nl(line) == 0)
return (line);
while (line[len] != '\n')
len++;
len++;
new = (char *) malloc(len + 1);
len = 0;
while (line[len] != '\n')
new[i++] = line[len++];
new[i++] = '\n';
new[i] = 0;
free(line);
return (new);
}
char *read_file(int fd, int *end)
{
char *readed;
int nb;
char *tmp;
readed = (char *) malloc(BUFFER_SIZE + 1);
nb = read(fd, readed, BUFFER_SIZE);
if (nb <= 0)
{
*end = 10;
free(readed);
return (NULL);
}
if (nb < BUFFER_SIZE)
{
readed[nb] = 0;
tmp = ft_strdup(readed);
free(readed);
return (tmp);
}
readed[BUFFER_SIZE] = 0;
return (readed);
}
char *get_next_line(int fd)
{
static char *remain[1024];
char *line;
int end;
end = 0;
if (fd < 0)
return (NULL);
if (remain[fd])
line = ft_strdup(remain[fd]);
else
line = read_file(fd, &end);
while (fd >= 0)
{
if (is_nl(line) || end)
{
remain[fd] = new_remain(line, remain[fd]);
return (new_line(line));
}
line = ft_strjoin(line, read_file(fd, &end));
}
return (NULL);
}