-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line_bonus.c
More file actions
120 lines (111 loc) · 2.67 KB
/
get_next_line_bonus.c
File metadata and controls
120 lines (111 loc) · 2.67 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: alisharu <marvin@42.fr> #+# +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025-05-11 10:58:19 by alisharu #+# #+# */
/* Updated: 2025-05-11 10:58:19 by alisharu ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *future_next_line(char *line)
{
int count;
char *buffer;
int i;
i = 0;
count = 0;
while (line[count] && line[count] != '\n')
count++;
if (!line[count])
{
free(line);
line = NULL;
return (NULL);
}
buffer = (char *)malloc(sizeof(char) * (ft_strlen(line) - count));
if (buffer == NULL)
{
free(line);
line = NULL;
return (NULL);
}
while (line[++count])
buffer[i++] = line[count];
buffer[i] = '\0';
return (free (line), buffer);
}
char *ft_cut_str(char *line)
{
int count;
int i;
char *buffer;
count = 0;
i = 0;
while (line[count] && line[count] != '\n')
count++;
buffer = (char *)malloc(sizeof(char) * (count + 2));
if (buffer == NULL)
return (NULL);
while (line[i] && i < count)
{
buffer[i] = line[i];
i++;
}
if (line[i] == '\n')
buffer[i++] = '\n';
buffer[i] = '\0';
return (buffer);
}
void ft_get_line(int fd, char **line)
{
char *buffer;
int bytes;
bytes = 0;
buffer = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (buffer == NULL)
return ;
while (1)
{
bytes = read(fd, buffer, BUFFER_SIZE);
if (bytes == -1)
{
free(*line);
*line = NULL;
break ;
}
if (bytes == 0)
break ;
buffer[bytes] = '\0';
*line = ft_strjoin (*line, buffer);
if (ft_strchr(*line, '\n') != NULL)
break ;
}
free(buffer);
}
char *get_next_line(int fd)
{
static char *line[OPEN_MAX] = {0};
char *curr_line;
curr_line = NULL;
if ((fd < 3 && fd != 0) || BUFFER_SIZE <= 0)
return (NULL);
ft_get_line(fd, &line[fd]);
if (!line[fd] || (line[fd] && !*line[fd]))
{
free (line[fd]);
line[fd] = NULL;
return (NULL);
}
curr_line = ft_cut_str(line[fd]);
if (curr_line && !curr_line[0])
{
free (curr_line);
curr_line = NULL;
return (NULL);
}
line[fd] = future_next_line(line[fd]);
return (curr_line);
}