-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_next_line.c
86 lines (78 loc) · 2.37 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lkaser <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/06 20:28:19 by lkaser #+# #+# */
/* Updated: 2018/07/06 20:28:21 by lkaser ### ########.fr */
/* */
/* ************************************************************************** */
#define ASSERT_FAIL return(-1)
#include "libft.h"
static t_fileinfo *new_fi(const int fd)
{
t_fileinfo *fi;
fi = malloc(sizeof(t_fileinfo));
fi->fd = fd;
fi->i = 0;
fi->fill = 0;
ft_bzero(fi->buff, GNL_BUFF + 1);
return (fi);
}
static char is_fd(const void *a, const void *b)
{
return (((t_fileinfo*)a)->fd == *(const int*)b);
}
static int fill_line(t_fileinfo *fi, char **line)
{
long ret;
long end;
char *tmp;
while ((ret = read(fi->fd, fi->buff, GNL_BUFF)) > 0)
{
fi->fill = ret;
fi->buff[ret] = '\0';
if ((end = ft_strchr(fi->buff, '\n') - fi->buff) >= 0)
{
fi->buff[end] = '\0';
fi->i = end + 1;
ASSERT(tmp = ft_strjoin(*line, fi->buff));
free(*line);
*line = tmp;
return (1);
}
ASSERT(tmp = ft_strjoin(*line, fi->buff));
free(*line);
*line = tmp;
fi->fill = 0;
}
ASSERT(ret >= 0);
return (*line != NULL);
}
int get_next_line(const int fd, char **line)
{
static t_list *fdlst = NULL;
t_fileinfo *fi;
t_list *node;
long end;
ASSERT(line && fd >= 0);
*line = NULL;
if (!(node = ft_lstfind(fdlst, is_fd, &fd)))
node = ft_lstpush(&fdlst, new_fi(fd), sizeof(t_fileinfo));
fi = (t_fileinfo*)node->content;
if (fi->fill - fi->i > 0)
{
end = ft_strchr(fi->buff + fi->i, '\n') - (fi->buff + fi->i);
end = end >= 0 ? fi->i + end : fi->fill;
fi->buff[end] = '\0';
ASSERT(*line = ft_strdup(fi->buff + fi->i));
fi->i = end + 1;
if (end < fi->fill)
return (1);
}
if ((end = fill_line(fi, line)) <= 0)
ft_lstrm(&fdlst, node);
return (end);
}