-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
100 lines (91 loc) · 2.4 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.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mohaben- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/09 13:42:51 by mohaben- #+# #+# */
/* Updated: 2025/01/13 12:28:04 by mohaben- ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
char *ft_fill(int fd, char *saved_chars, char *buffer)
{
ssize_t bytes_read;
char *tmp;
bytes_read = 1;
while (bytes_read > 0)
{
bytes_read = read(fd, buffer, BUFFER_SIZE);
if (bytes_read == -1)
{
free(saved_chars);
saved_chars = NULL;
return (NULL);
}
if (bytes_read == 0)
break ;
buffer[bytes_read] = '\0';
tmp = saved_chars;
saved_chars = ft_strjoin(tmp, buffer);
free(tmp);
if (saved_chars == NULL)
return (NULL);
if (ft_strchr(saved_chars, '\n'))
break ;
}
return (saved_chars);
}
char *ft_extract_line(char *data)
{
char *line;
size_t i;
if (data == NULL)
return (NULL);
i = 0;
while (data[i] && data[i] != '\n')
i++;
if (data[i] == '\n')
i++;
line = ft_substr(data, 0, i);
return (line);
}
char *ft_save_chars_left(char *data)
{
size_t i;
char *chars_left;
if (data == NULL)
return (NULL);
i = 0;
while (data[i] && data[i] != '\n')
i++;
if (data[i] == '\n')
i++;
if (data[i] == '\0')
return (NULL);
chars_left = ft_substr(data, i, ft_strlen(data) - i);
return (chars_left);
}
char *get_next_line(int fd)
{
static char *saved_chars;
char *buffer;
char *line;
char *data;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, NULL, 0) < 0)
{
free(saved_chars);
saved_chars = NULL;
return (NULL);
}
buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (buffer == NULL)
return (NULL);
data = ft_fill(fd, saved_chars, buffer);
free(buffer);
line = ft_extract_line(data);
saved_chars = ft_save_chars_left(data);
free(data);
return (line);
}