This repository has been archived by the owner on Apr 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
83 lines (75 loc) · 2.34 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: magrab <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/19 18:28:44 by magrab #+# #+# */
/* Updated: 2018/12/22 15:53:03 by magrab ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
/*
** Work
** Use only if \n inside tabfd
*/
static int isinbuffer(const int fd, char **line, char *tabfd[OPEN_MAX])
{
int npos;
char *tmp;
npos = ft_strsrchr(tabfd[fd], '\n');
if (!(tmp = malloc((npos + 1) * sizeof(char))))
return (-1);
tmp[npos] = 0;
ft_strncpy(tmp, tabfd[fd], npos);
*line = tmp;
tmp = ft_strdup(tabfd[fd] + npos + 1);
if (tmp && *tmp == 0)
ft_strdel(&tmp);
if (tabfd[fd])
ft_strdel(&tabfd[fd]);
tabfd[fd] = tmp;
return (1);
}
static int gnl(const int fd, char **line, int xread, char *tabfd[OPEN_MAX])
{
char reader[BUFF_SIZE + 1];
char *save;
reader[BUFF_SIZE] = 0;
while (ft_strchr(tabfd[fd], '\n') == NULL && xread == BUFF_SIZE)
{
xread = read(fd, reader, BUFF_SIZE);
save = ft_strnjoin(tabfd[fd], reader, xread);
ft_strdel(&tabfd[fd]);
tabfd[fd] = save;
}
if (ft_strchr(tabfd[fd], '\n'))
return (isinbuffer(fd, line, tabfd));
if (0 <= xread && tabfd[fd][0])
{
*line = tabfd[fd];
tabfd[fd] = NULL;
return (1);
}
return (-1);
}
int get_next_line(const int fd, char **line)
{
static char *tabfd[OPEN_MAX];
int xread;
if (fd < 0 || fd >= OPEN_MAX || line == NULL || BUFF_SIZE < 1)
return (-1);
xread = BUFF_SIZE;
if (tabfd[fd] == NULL)
{
if (!(tabfd[fd] = ft_memalloc((BUFF_SIZE + 1) * sizeof(char))))
return (-1);
if ((xread = read(fd, tabfd[fd], BUFF_SIZE)) == 0 && tabfd[fd][0] == 0)
{
ft_strdel(&tabfd[fd]);
return (0);
}
}
return (gnl(fd, line, xread, tabfd));
}