-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
92 lines (85 loc) · 2.38 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
92
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lsauvage <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/07 18:41:03 by lsauvage #+# #+# */
/* Updated: 2018/09/20 15:14:03 by lsauvage ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "./libft.h"
static int gnl_write(t_list **l, char **line, int res)
{
char *str;
t_list *tmp;
int i;
int j;
int k;
i = 0;
k = 0;
while (*l && i != -1 && !(j = 0))
{
str = (char *)(*l)->content;
while (str[j] && str[j] != '\n')
(*line)[i++] = str[j++];
if (str[j] == '\n')
i = -1;
tmp = *l;
*l = (*l)->next;
free(tmp->content);
free(tmp);
k++;
}
return (res);
}
static int gnl_read(t_list **list, int fd, size_t len, t_buff *buff)
{
int ret;
t_list *tmp;
size_t i;
size_t j;
j = 0;
while (!buff->index && ++j && (ret = read(fd, buff->mem, BUFF_SIZE)))
{
i = 0;
buff->mem[ret] = 0;
if (ret == -1 || !(tmp = ft_lstnew(buff->mem, ret + 1)))
return (-1);
ft_lstadd_end(list, tmp);
while (buff->mem[i] && buff->mem[i] != '\n' && ++len > 0)
i++;
if (buff->mem[i] == '\n' && (buff->index = i))
return (1);
buff->index = 0;
}
return (j == 0 ? 1 : 0);
}
int get_next_line(const int fd, char **line)
{
t_list *list;
static t_buff buff;
size_t len;
int i;
if (BUFF_SIZE <= 0)
return (-1);
len = 0;
list = NULL;
i = buff.index;
if (buff.index)
{
if (!(list = ft_lstnew(&(buff.mem[i]), ft_strlen(&(buff.mem[i])) + 1)))
return (-1);
while (buff.mem[i] && buff.mem[i] != '\n' && ++len > 0)
i++;
if (buff.mem[i] == '\n' && ++i)
buff.index += (i - buff.index);
else
buff.index = 0;
}
if ((i = gnl_read(&list, fd, len, &buff)) == -1)
return (-1);
return ((*line = ft_strnew(len)) ? gnl_write(&list, line, i) : -1);
}