-
Notifications
You must be signed in to change notification settings - Fork 6
/
get_next_line.c
91 lines (84 loc) · 2.07 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rchallie <rchallie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/18 10:20:38 by rchallie #+# #+# */
/* Updated: 2019/11/04 10:24:41 by rchallie ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_save(char *save)
{
char *rtn;
int i;
int j;
i = 0;
j = 0;
if (!save)
return (0);
while (save[i] && save[i] != '\n')
i++;
if (!save[i])
{
free(save);
return (0);
}
if (!(rtn = malloc(sizeof(char) * ((ft_strlen(save) - i) + 1))))
return (0);
i++;
while (save[i])
rtn[j++] = save[i++];
rtn[j] = '\0';
free(save);
return (rtn);
}
char *get_line(char *str)
{
int i;
char *rtn;
i = 0;
if (!str)
return (0);
while (str[i] && str[i] != '\n')
i++;
if (!(rtn = malloc(sizeof(char) * (i + 1))))
return (0);
i = 0;
while (str[i] && str[i] != '\n')
{
rtn[i] = str[i];
i++;
}
rtn[i] = '\0';
return (rtn);
}
int get_next_line(int fd, char **line)
{
char *buff;
static char *save;
int reader;
reader = 1;
if (fd < 0 || !line || BUFFER_SIZE <= 0)
return (-1);
if (!(buff = malloc(sizeof(char) * (BUFFER_SIZE + 1))))
return (-1);
while (!has_return(save) && reader != 0)
{
if ((reader = read(fd, buff, BUFFER_SIZE)) == -1)
{
free(buff);
return (-1);
}
buff[reader] = '\0';
save = join_str(save, buff);
}
free(buff);
*line = get_line(save);
save = get_save(save);
if (reader == 0)
return (0);
return (1);
}