-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
100 lines (90 loc) · 2.49 KB
/
get_next_line_bonus.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
93
94
95
96
97
98
99
100
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: roferrei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/22 01:00:04 by roferrei #+# #+# */
/* Updated: 2022/08/12 17:36:40 by roferrei ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *str;
if (!s)
return (NULL);
if (ft_strlen(s) < start + 1)
return (ft_strdup(""));
if (ft_strlen(&s[start]) < len)
len = ft_strlen(&s[start]);
str = (char *)malloc(sizeof(*s) * (len + 1));
if (!str)
return (NULL);
ft_strlcpy(str, s + start, len + 1);
return (str);
}
static char *read_txt(char *rest, int fd)
{
char *buffer;
int text_read;
char *aux;
buffer = malloc(sizeof(char) * (BUFFER_SIZE + 1));
while (ft_strchr(rest, '\n') == NULL)
{
text_read = read(fd, buffer, BUFFER_SIZE);
if (text_read <= 0)
break ;
buffer[text_read] = '\0';
aux = rest;
rest = ft_strjoin(rest, buffer);
free (aux);
}
free (buffer);
return (rest);
}
static void save_me(char **rest)
{
if (**rest == '\0')
{
free(*rest);
*rest = NULL;
}
}
static char *get_line(char **rest)
{
char *i;
char *temp;
char *aux;
i = ft_strchr(*rest, '\n');
save_me(rest);
if (i == NULL)
{
temp = *rest;
*rest = NULL;
}
else
{
aux = *rest;
temp = ft_substr(*rest, 0, (i - *rest + 1));
if (i[1] != '\0')
*rest = ft_strdup(&i[1]);
else
*rest = NULL;
free(aux);
}
return (temp);
}
char *get_next_line(int fd)
{
static char *rest[1024]; // vetor com a quantidade de arquivos que posso trabalhar.
char *line;
if (fd < 0 || fd > 1024 || BUFFER_SIZE <= 0) //verificar fd não existir, retornar NULL / testar se fd é arbitrário ou inexistente e retornar NULL
return (0);
if (rest[fd] == NULL)
rest[fd] = ft_strdup("");
rest[fd] = read_txt(rest[fd], fd);
line = get_line(&rest[fd]);
return (line);
}