-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
78 lines (72 loc) · 2.06 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mavinici <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/03 11:24:44 by marcus #+# #+# */
/* Updated: 2022/04/21 09:31:22 by mavinici ### ########.fr */
/* */
/* ************************************************************************** */
#include <libft.h>
static int add_line(char **str, char **line)
{
int size;
char *tmp;
size = 0;
while ((*str)[size] != '\n' && (*str)[size])
size++;
if ((*str)[size] == '\0')
{
*line = ft_strdup(*str);
if (*str != NULL)
{
free(*str);
*str = NULL;
}
return (0);
}
*line = ft_line(*str, size);
tmp = ft_strdup((*str) + size + 1);
free(*str);
*str = tmp;
return (1);
}
static int output(char **str, char **line, ssize_t size)
{
if (size < 0 || !line || BUFFER_SIZE <= 0)
return (-1);
else if (size == 0 && *str == NULL)
{
*line = ft_strdup("");
return (0);
}
return (add_line(str, line));
}
int get_next_line(int fd, char **line)
{
static char *str[OPEN_MAX];
t_var var;
var.buffer = malloc(BUFFER_SIZE + 1);
if (!var.buffer)
return (-1);
var.size = read(fd, var.buffer, BUFFER_SIZE);
while (var.size > 0)
{
var.buffer[var.size] = '\0';
if (str[fd] == NULL)
str[fd] = ft_strdup(var.buffer);
else
{
var.tmp = ft_strjoin(str[fd], var.buffer);
free(str[fd]);
str[fd] = var.tmp;
}
if (ft_strchr(str[fd], '\n'))
break ;
var.size = read(fd, var.buffer, BUFFER_SIZE);
}
free(var.buffer);
return (output(&str[fd], line, var.size));
}