-
Notifications
You must be signed in to change notification settings - Fork 2
/
get_next_line_bonus.c
84 lines (75 loc) · 2.19 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: daelee <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/11 21:01:29 by daelee #+# #+# */
/* Updated: 2020/04/19 01:51:22 by daelee ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
int is_newline(char *backup)
{
int i;
i = 0;
while (backup[i])
{
if (backup[i] == '\n')
return (i);
i++;
}
return (-1);
}
int split_line(char **backup, char **line, int cut_idx)
{
char *temp;
int len;
(*backup)[cut_idx] = '\0';
*line = ft_strdup(*backup);
len = ft_strlen(*backup + cut_idx + 1);
if (len == 0)
{
free(*backup);
*backup = 0;
return (1);
}
temp = ft_strdup(*backup + cut_idx + 1);
free(*backup);
*backup = temp;
return (1);
}
int return_all(char **backup, char **line, int read_size)
{
int cut_idx;
if (read_size < 0)
return (-1);
if (*backup && (cut_idx = is_newline(*backup)) >= 0)
return (split_line(backup, line, cut_idx));
else if (*backup)
{
*line = *backup;
*backup = 0;
return (0);
}
*line = ft_strdup("");
return (0);
}
int get_next_line(int fd, char **line)
{
static char *backup[OPEN_MAX];
char buf[BUFFER_SIZE + 1];
int read_size;
int cut_idx;
if ((fd < 0) || (line == 0) || (BUFFER_SIZE <= 0))
return (-1);
while ((read_size = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[read_size] = '\0';
backup[fd] = ft_strjoin(backup[fd], buf);
if ((cut_idx = is_newline(backup[fd])) >= 0)
return (split_line(&backup[fd], line, cut_idx));
}
return (return_all(&backup[fd], line, read_size));
}