-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
81 lines (72 loc) · 2.09 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: youkim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/12 15:27:09 by youkim #+# #+# */
/* Updated: 2021/06/15 14:33:29 by youkim ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
int where_newline(char *backup)
{
int i;
i = -1;
while (backup[++i])
if (backup[i] == '\n')
return (i);
return (-1);
}
int pop_line(char **backup, char **line, int cut_where)
{
char *temp;
(*backup)[cut_where] = '\0';
*line = ft_strdup(*backup);
if (!ft_strlen(*backup + cut_where + 1))
{
free(*backup);
*backup = 0;
}
else
{
temp = ft_strdup(*backup + cut_where + 1);
free(*backup);
*backup = temp;
}
return (1);
}
int result(char **backup, char **line)
{
int cut_where;
if (*backup && (cut_where = where_newline(*backup)) >= 0)
return (pop_line(backup, line, cut_where));
else if (*backup)
{
*line = *backup;
*backup = 0;
}
else
*line = ft_strdup("");
return (0);
}
int get_next_line(int fd, char **line)
{
int len;
int cut_where;
char buffer[BUFFER_SIZE + 1];
static char *backup[OPEN_MAX];
if ((fd < 0) || (line == 0) || (BUFFER_SIZE <= 0))
return (-1);
while ((len = read(fd, buffer, BUFFER_SIZE)) > 0)
{
buffer[len] = '\0';
backup[fd] = ft_strjoin(backup[fd], buffer);
if ((cut_where = where_newline(backup[fd])) >= 0)
return (pop_line(&backup[fd], line, cut_where));
}
if (len < 0)
return (-1);
return (result(&backup[fd], line));
}