-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
122 lines (111 loc) · 2.56 KB
/
get_next_line.c
File metadata and controls
122 lines (111 loc) · 2.56 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edesaint <edesaint@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/12 16:07:55 by edesaint #+# #+# */
/* Updated: 2023/01/17 15:21:20 by edesaint ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int ft_strlen(const char *s)
{
int i;
if (!s)
return (0);
i = 0;
while (s[i] != '\0')
i++;
return (i);
}
int found_newline(t_list *lst)
{
t_list *current;
int i;
if (lst == NULL)
return (0);
current = ft_lstlast(lst);
i = 0;
while (current->content[i] && current->content[i] != '\n')
i++;
if (current->content[i] && current->content[i] == '\n')
return (1);
return (0);
}
void add_to_stash(t_list **lst, char *buf, int readed)
{
t_list *new;
t_list *last;
int i;
new = (t_list *) malloc(sizeof(t_list));
if (!new)
return ;
new->next = NULL;
new->content = (char *) malloc(sizeof(char) * (readed + 1));
if (!new->content)
return ;
i = 0;
while (buf[i] && i < readed)
{
new->content[i] = buf[i];
i++;
}
new->content[i] = '\0';
if (*lst)
{
last = ft_lstlast(*lst);
last->next = new;
}
else
*lst = new;
}
void read_and_stach(int fd, t_list **lst)
{
char *buf;
int readed;
readed = 1;
while (!found_newline(*lst) && readed != 0)
{
buf = (char *) malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buf)
return ;
readed = (int) read(fd, buf, BUFFER_SIZE);
if ((*lst == NULL && readed == 0) || readed == -1)
{
free(buf);
return ;
}
buf[readed] = '\0';
add_to_stash(lst, buf, readed);
free(buf);
}
}
char *get_next_line(int fd)
{
static t_list *lst;
char *line;
if (BUFFER_SIZE <= 0 || fd < 0 || fd >= 1024)
return (NULL);
line = NULL;
read_and_stach(fd, &lst);
if (!lst)
return (NULL);
line = extract_line(lst);
if (line)
{
if (line[0] == '\0')
{
free(line);
line = NULL;
}
}
if (lst)
{
clean_stash(&lst);
if (lst->content[0] == '\0')
free_stash(&lst, 2);
}
return (line);
}