-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
106 lines (97 loc) · 2.36 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
101
102
103
104
105
106
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dsoroko <dsoroko@student.s19.be> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/23 11:21:36 by dsoroko #+# #+# */
/* Updated: 2022/05/25 11:10:35 by dsoroko ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *make_new_line(char *str)
{
int i;
char *line;
i = 0;
if (!str[i])
return (NULL);
while (str[i] && str[i] != '\n')
i++;
line = malloc(sizeof(char) * (i + 2));
if (!line)
return (NULL);
i = 0;
while (str[i] && str[i] != '\n')
{
line[i] = str[i];
i++;
}
if (str[i] == '\n')
{
line[i] = str[i];
i++;
}
line[i] = '\0';
return (line);
}
char *clean_the_rest(char *str)
{
int i;
int j;
char *new_str;
i = 0;
while (str[i] && str[i] != '\n')
i++;
if (str[i] == '\0')
{
free(str);
return (NULL);
}
new_str = malloc((ft_strlen(str) - i + 1) * sizeof(char));
if (!new_str)
return (NULL);
i++;
j = 0;
while (str[i] != '\0')
new_str[j++] = str[i++];
new_str[j] = '\0';
free(str);
return (new_str);
}
char *read_and_stash(int fd, char *str)
{
int char_count;
char *temp;
temp = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!temp)
return (NULL);
char_count = 1;
while (!ft_strchr(str, '\n') && char_count != 0)
{
char_count = read(fd, temp, BUFFER_SIZE);
if (char_count == -1)
{
free(temp);
return (NULL);
}
temp[char_count] = '\0';
str = ft_strjoin(str, temp);
}
free(temp);
return (str);
}
char *get_next_line(int fd)
{
char *line;
static char *stash[OPEN_MAX];
if (fd < 0 || BUFFER_SIZE <= 0 || fd > OPEN_MAX)
return (NULL);
stash[fd] = read_and_stash(fd, stash[fd]);
if (!stash[fd])
return (NULL);
line = make_new_line(stash[fd]);
stash[fd] = clean_the_rest(stash[fd]);
return (line);
}