-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
77 lines (72 loc) · 2.34 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tvasilev <tvasilev@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/19 16:34:34 by tvasilev #+# #+# */
/* Updated: 2023/02/04 14:05:32 by tvasilev ### ########.fr */
/* */
/* ************************************************************************** */
#include"get_next_line_bonus.h"
static char *freeing_shit(char **buff, char *result, int free_result)
{
free(*buff);
*buff = NULL;
if (free_result)
{
free(result);
}
return (NULL);
}
static char *helper(int fd, char **buff, char *result, int *chars_read)
{
while ((!ft_strchr1(*buff, '\n') && **buff != *"") || **buff == '\0')
{
result = ft_strjoin1(result, *buff, ft_strlen1(*buff) + 1);
*chars_read = read(fd, *buff, BUFFER_SIZE);
(*buff)[*chars_read] = 0;
if (*chars_read < 0)
return (freeing_shit(buff, result, 1));
if (*chars_read == 0)
{
if (*result == *"")
return (freeing_shit(buff, result, 1));
return (result);
}
}
if (ft_strchr1(*buff, '\n'))
{
result = ft_strjoin1(result, *buff, ft_strchr1(*buff, '\n')
- *buff + 2);
ft_strlcpy1(*buff, ft_strchr1(*buff, '\n') + 1,
ft_strlen1(ft_strchr1(*buff, '\n')));
}
if (result == 0)
return (freeing_shit(buff, result, 1));
return (result);
}
char *get_next_line(int fd)
{
static char *buff[FOPEN_MAX];
char *result;
int chars_read;
result = 0;
chars_read = 0;
if (fd == -1)
return (freeing_shit(&(buff[0]), result, 0));
if (fd < 0 || fd > FOPEN_MAX)
return (NULL);
if (!buff[fd])
{
buff[fd] = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buff[fd])
return (NULL);
chars_read = read(fd, buff[fd], BUFFER_SIZE);
if (chars_read < 0)
return (freeing_shit(&(buff[fd]), result, 0));
buff[fd][chars_read] = 0;
}
return (helper(fd, &(buff[fd]), result, &chars_read));
}