-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
125 lines (115 loc) · 2.92 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aheinane <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/18 09:17:19 by aheinane #+# #+# */
/* Updated: 2024/10/28 11:39:16 by aheinane ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_exist(char *str)
{
if (!str)
{
str = malloc(1);
if (!str)
return (NULL);
*str = 0;
}
return (str);
}
char *next_spot(char *storage)
{
int i;
int nextspot_index;
char *next_spot;
nextspot_index = 0;
i = 0;
while (storage[i] && storage[i] != '\n')
i++;
if (storage[i] == '\0' || storage[i + 1] == '\0')
{
free(storage);
return (NULL);
}
next_spot = malloc(sizeof(char) * (gnl_strlen(storage) - i));
if (!next_spot)
return (free_function(&storage));
i++;
while (storage[i])
next_spot[nextspot_index++] = storage[i++];
next_spot[nextspot_index] = '\0';
free(storage);
return (next_spot);
}
char *ft_get_line(char *storage)
{
char *temp;
int i;
i = 0;
if (!storage[i])
return (NULL);
while (storage[i] && storage[i] != '\n')
i++;
if (storage[i] != '\n')
temp = malloc(i + 1);
else
temp = malloc(i + 2);
i = 0;
if (!temp)
return (NULL);
while (storage[i] && storage[i] != '\n')
{
temp[i] = storage[i];
i++;
}
if (storage[i] && storage[i] == '\n')
temp[i++] = '\n';
temp[i] = '\0';
return (temp);
}
char *ft_read(int fd, char *storage)
{
char *buffer;
int how_many_bytes;
storage = ft_exist(storage);
if (!storage)
return (NULL);
buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buffer)
return (free_function(&storage));
how_many_bytes = 1;
while (how_many_bytes > 0 && !gnl_strchr(storage, '\n'))
{
how_many_bytes = read (fd, buffer, BUFFER_SIZE);
if (how_many_bytes == -1)
return (free_function(&storage));
buffer[how_many_bytes] = '\0';
storage = gnl_strjoin(storage, buffer);
if (!storage)
return (free_function(&storage));
}
free(buffer);
return (storage);
}
char *get_next_line(int fd)
{
static char *storage;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0 || read (fd, 0, 0) < 0)
return (free_function(&storage));
storage = ft_read(fd, storage);
if (!storage)
return (free_function(&storage));
line = ft_get_line(storage);
storage = next_spot(storage);
if (!line || !storage)
{
free(storage);
storage = NULL;
}
return (line);
}