-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
109 lines (98 loc) · 2.32 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tgiraudo <tgiraudo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/11 12:09:46 by tgiraudo #+# #+# */
/* Updated: 2022/11/23 10:55:37 by tgiraudo ### ########.fr */
/* */
/* ************************************************************************** */
#include"get_next_line.h"
char *ft_free(char *save, char *buffer)
{
char *temp;
temp = ft_strjoin(save, buffer);
free(save);
return (temp);
}
char *ft_line(char *save)
{
int i;
char *line;
i = 0;
if (!save[i])
return (NULL);
while (save[i] && save[i] != '\n')
i++;
line = ft_calloc(i + 2, sizeof(char));
i = 0;
while (save[i] && save[i] != '\n')
{
line[i] = save[i];
i++;
}
if (save[i] == '\n')
line[i++] = '\n';
return (line);
}
char *ft_next_line(char *save)
{
int i;
int j;
char *next_line;
i = 0;
while (save[i] && save[i] != '\n')
i++;
if (!save[i])
{
free (save);
return (NULL);
}
next_line = ft_calloc(ft_strlen(save) - i + 1, sizeof(char));
i++;
j = 0;
while (save[i])
{
next_line[j] = save[i++];
j++;
}
free(save);
return (next_line);
}
char *ft_read_buf(char *save, int fd)
{
char *buffer;
int size;
buffer = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
size = 1;
while (size && !new_line(save))
{
size = read(fd, buffer, BUFFER_SIZE);
if (size < 0)
{
free(buffer);
return (NULL);
}
buffer[size] = '\0';
save = ft_free(save, buffer);
}
free(buffer);
return (save);
}
char *get_next_line(int fd)
{
static char *save;
char *line;
if (fd < 0 || read(fd, 0, 0) < 0 || BUFFER_SIZE <= 0)
return (NULL);
if (!save)
save = ft_calloc(1, sizeof(char));
save = ft_read_buf(save, fd);
if (!save)
return (NULL);
line = ft_line(save);
save = ft_next_line(save);
return (line);
}