-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
123 lines (113 loc) · 2.87 KB
/
get_next_line.c
File metadata and controls
123 lines (113 loc) · 2.87 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rrollin <rrollin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/15 09:53:57 by rrollin #+# #+# */
/* Updated: 2022/04/15 13:46:00 by rrollin ### ########.fr */
/* */
/* ************************************************************************** */
#include"get_next_line.h"
t_dict_cell *ft_lstnew(int fd)
{
t_dict_cell *list;
list = (t_dict_cell *) malloc(sizeof(t_dict_cell));
if (!list)
return (NULL);
list->next = NULL;
list->fd = fd;
list->buf = malloc(1);
list->buf[0] = 0;
list->ret = BUFFER_SIZE;
return (list);
}
t_dict_cell *ft_lstget_cell(int fd, t_dict_cell **list)
{
t_dict_cell *cell;
if (!(*list))
{
*list = ft_lstnew(fd);
if (!(*list))
return (NULL);
return (*list);
}
cell = *list;
while (cell->next && cell->fd != fd)
cell = cell->next;
if (!cell->next && cell->fd != fd)
{
cell->next = ft_lstnew(fd);
if (!cell->next)
return (NULL);
cell = cell->next;
}
return (cell);
}
int ft_read(char *str, t_dict_cell *cell, int fd)
{
str = malloc(BUFFER_SIZE + 1);
if (!str)
return (0);
cell->ret = read(fd, str, BUFFER_SIZE);
str[cell->ret] = 0;
cell->buf = ft_strjoin(cell->buf, str);
free(str);
if (!cell->buf)
return (0);
return (1);
}
char *ft_start_read(int fd, t_dict_cell **list, t_dict_cell **c)
{
char *str;
char *n;
if (!ft_loop_read(fd, (*c)))
{
str = NULL;
if ((*c)->buf[0])
str = (*c)->buf;
else
free((*c)->buf);
ft_lstdel_one(*c, list);
return (str);
}
else if (ft_chr((*c)->buf, '\n') >= 0)
{
str = ft_sub((*c)->buf, 0, ft_chr((*c)->buf, '\n') + 1);
n = ft_sub((*c)->buf, ft_chr((*c)->buf, 10) + 1, ft_chr((*c)->buf, 0));
free((*c)->buf);
(*c)->buf = n;
return (str);
}
str = (*c)->buf;
ft_lstdel_one(*c, list);
return (str);
}
char *get_next_line(int fd)
{
static t_dict_cell *list;
t_dict_cell *tp;
char *str;
char *new;
tp = ft_lstget_cell(fd, &list);
if (ft_chr(tp->buf, '\n') >= 0)
{
str = ft_sub(tp->buf, 0, ft_chr(tp->buf, '\n') + 1);
new = ft_sub(tp->buf, ft_chr(tp->buf, 10) + 1, ft_chr(tp->buf, 0));
free(tp->buf);
tp->buf = new;
}
else if (tp->ret < BUFFER_SIZE)
{
str = tp->buf;
ft_lstdel_one(tp, &list);
if (str[0])
return (str);
free(str);
return (NULL);
}
else
str = ft_start_read(fd, &list, &tp);
return (str);
}