-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
106 lines (97 loc) · 2.55 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
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.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: flverge <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/04 10:24:42 by flverge #+# #+# */
/* Updated: 2023/10/17 15:20:43 by flverge ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *big_chunk(int fd, char *stash)
{
char *original_buffer;
int return_value_read;
return_value_read = 1;
original_buffer = malloc(BUFFER_SIZE + 1 * sizeof(char));
if (!original_buffer)
return (NULL);
while (return_value_read != 0 && ft_strchr(stash, '\n') == NULL)
{
return_value_read = read(fd, original_buffer, BUFFER_SIZE);
if (return_value_read == -1)
{
free(original_buffer);
return (NULL);
}
original_buffer[return_value_read] = '\0';
stash = ft_strjoin(stash, original_buffer);
}
free(original_buffer);
return (stash);
}
char *extract_before_n(char *stash)
{
char *temp;
int size;
size = 0;
if (!stash[size])
return (NULL);
while (stash[size] != '\n' && stash[size])
size++;
temp = (char *)malloc((size + 2) * sizeof(char));
if (!temp)
return (NULL);
size = 0;
while (stash[size] != '\n' && stash[size])
{
temp[size] = stash[size];
size++;
}
if (stash[size] == '\n')
{
temp[size] = stash[size];
size++;
}
temp[size] = '\0';
return (temp);
}
char *extract_after_n(char *stash)
{
char *temp;
int i;
int j;
i = 0;
while (stash[i] != '\n' && stash[i])
i++;
if (!stash[i])
{
free(stash);
return (NULL);
}
temp = (char *)malloc((ft_strlen(stash) - i + 1) * sizeof(char));
if (!temp)
return (NULL);
j = 0;
i++;
while (stash[i] != '\0')
temp[j++] = stash[i++];
temp[j] = '\0';
free(stash);
return (temp);
}
char *get_next_line(int fd)
{
char *current_line;
static char *stash;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
stash = big_chunk(fd, stash);
if (!stash)
return (NULL);
current_line = extract_before_n(stash);
stash = extract_after_n(stash);
return (current_line);
}