-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
114 lines (105 loc) · 2.44 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: maxweert <maxweert@student.s19.be> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/16 15:21:55 by maxweert #+# #+# */
/* Updated: 2024/10/17 21:30:45 by maxweert ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <string.h>
#include "get_next_line.h"
static char *set_line(char **line)
{
char *left;
char *tmp;
size_t i;
if (!(*line))
return (NULL);
i = 0;
while ((*line)[i] && (*line)[i] != '\n')
i++;
if ((*line)[i] == '\0' || (*line)[i + 1] == '\0')
return (NULL);
left = ft_substr(*line, i + 1, ft_strlen(*line) - i);
tmp = *line;
*line = ft_substr(tmp, 0, i + 1);
free(tmp);
if (!(*line))
{
free(left);
left = NULL;
return (NULL);
}
return (left);
}
static char *read_fd(int fd, char *left, char *buffer)
{
char *tmp;
int rd;
while (1)
{
rd = read(fd, buffer, BUFFER_SIZE);
if (rd < 0)
{
free(left);
return (NULL);
}
if (rd == 0)
break ;
buffer[rd] = '\0';
if (!left)
left = ft_calloc(1, sizeof(char));
if (!left)
return (NULL);
tmp = ft_strjoin(left, buffer);
free(left);
left = tmp;
if (ft_strchr(buffer, '\n'))
break ;
}
return (left);
}
char *get_next_line(int fd)
{
static char *left;
char *line;
char *buffer;
if (fd < 0)
return (NULL);
buffer = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
if (!buffer)
{
free(left);
left = NULL;
return (NULL);
}
line = read_fd(fd, left, buffer);
free(buffer);
buffer = NULL;
left = set_line(&line);
if (!line || line[0] == '\0')
{
free(left);
left = NULL;
return (NULL);
}
return (line);
}
// int main()
// {
// int fd;
// char *line;
// fd = open("multiple_nl.txt", O_RDONLY);
// line = get_next_line(fd);
// while (line)
// {
// printf("%s", line);
// line = get_next_line(fd);
// }
// close(fd);
// return (0);
// }