-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
86 lines (77 loc) · 2.25 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: gwasserf <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/29 11:34:23 by gwasserf #+# #+# */
/* Updated: 2019/06/29 11:42:07 by gwasserf ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_get_fdlist(int fd, t_list **alst)
{
t_list *head;
if (!(*alst))
*alst = ft_lstnew("\0", fd);
head = *alst;
while (head)
{
if ((int)head->content_size == fd)
return (head);
head = head->next;
}
head = ft_lstnew("\0", fd);
ft_lstadd(alst, head);
return (head);
}
int fetch_line(char **store, char **line)
{
char *temp;
char *ptr;
char *end;
if ((*store)[0] == 4)
return (0);
if ((end = ft_strchr(*store, 4)))
if (!(ft_strchr(*store, '\n')))
*end = '\n';
temp = ft_strdup(*store);
ptr = ft_strchr(temp, '\n');
*ptr = 0;
*line = ft_strdup(temp);
free(*store);
*store = ft_strdup((ptr + 1));
free(temp);
return (1);
}
void read_until_line(int fd, char **store)
{
char buffer[BUFF_SIZE + 2];
char *temp;
int ret;
while (!ft_strchr(*store, '\n'))
{
ret = read(fd, buffer, BUFF_SIZE);
buffer[ret] = ((ret < BUFF_SIZE) && (fd != 0)) ? 4 : 0;
buffer[ret + 1] = 0;
temp = ft_strdup(*store);
free(*store);
*store = ft_strjoin(temp, buffer);
free(temp);
if (!ret)
return ;
}
}
int get_next_line(int fd, char **line)
{
static t_list *list;
t_list *current;
if (fd < 0 || !line || (read(fd, 0, 0) < 0))
return (-1);
current = ft_get_fdlist(fd, &list);
read_until_line(fd, (char **)¤t->content);
if (!(ft_strlen((char *)current->content)))
return (0);
return (fetch_line((char **)¤t->content, line));
}