-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
109 lines (99 loc) · 2.58 KB
/
get_next_line.c
File metadata and controls
109 lines (99 loc) · 2.58 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbeaufre <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/17 16:32:05 by rbeaufre #+# #+# */
/* Updated: 2019/11/28 21:11:25 by rbeaufre ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
t_fd_list *ft_locate_fd(t_fd_list **files, int fd)
{
t_fd_list *tmp;
t_fd_list *new;
tmp = *files;
while (tmp)
{
if (tmp->fd == fd)
return (tmp);
tmp = tmp->next;
}
if (!(new = (t_fd_list *)malloc(sizeof(t_fd_list))))
return (0);
if (!(new->str = (char *)malloc(sizeof(char))))
return (0);
(new->str)[0] = '\0';
new->fd = fd;
new->next = *files;
*files = new;
return (new);
}
int ft_bks(char *str)
{
int i;
i = 0;
while (str[i])
{
if (str[i] == '\n')
return (i);
i++;
}
return (-1);
}
int ft_allocate_line(char *str, char **line)
{
int index;
if (ft_strlen(str) == 0)
return (0);
index = ft_bks(str);
if (index == -1)
{
if (!(*line = ft_strnew(ft_strlen(str))))
return (-1);
ft_strncpy(*line, str, ft_strlen(str));
return (2);
}
if (index >= 0)
{
if (!(*line = ft_strnew(index)))
return (-1);
ft_strncpy(*line, str, index);
return (1);
}
return (-1);
}
void ft_swap_free(char **tmp, char *buf, char **str)
{
*tmp = ft_strjoin(*str, buf);
free(*str);
*str = *tmp;
}
int get_next_line(const int fd, char **line)
{
static t_fd_list *files = NULL;
t_fd_list *l;
char buf[BUFF_SIZE + 1];
int ret;
char *tmp;
if (line == NULL || fd < 0 || BUFF_SIZE < 1 || read(fd, buf, 0) < 0)
return (-1);
l = ft_locate_fd(&files, fd);
while ((ret = read(fd, buf, BUFF_SIZE)))
{
buf[ret] = '\0';
ft_swap_free(&tmp, buf, &(l->str));
if (ft_bks(l->str) >= 0)
break ;
}
ret = ft_allocate_line(l->str, line);
if (ret == -1)
return (-1);
tmp = ((ret == 1) ? (ft_strsub(l->str, ft_bks(l->str) + 1, \
ft_strlen(l->str) - ft_bks(l->str))) : ft_strsub(l->str, 0, 0));
free(l->str);
l->str = tmp;
return ((ret == 0) ? 0 : 1);
}