-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
110 lines (101 loc) · 2.3 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adiaz-be <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/10 08:38:58 by adiaz-be #+# #+# */
/* Updated: 2022/10/10 08:39:55 by adiaz-be ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_line(char *save)
{
int i;
char *str;
i = 0;
if (!save[i])
return (NULL);
while (save[i] && save[i] != '\n')
i++;
str = (char *)malloc(sizeof(char) * (i + 2));
if (!str)
return (NULL);
i = 0;
while (save[i] && save[i] != '\n')
{
str[i] = save[i];
i++;
}
if (save[i] == '\n')
{
str[i] = save[i];
i++;
}
str[i] = '\0';
return (str);
}
char *ft_save(char *save)
{
int i;
int pos;
char *str;
i = 0;
while (save[i] && save[i] != '\n')
i++;
if (!save[i])
{
free(save);
return (NULL);
}
str = (char *)malloc(sizeof(char) * (ft_strlen(save) - i + 1));
if (!str)
{
free(str);
return (NULL);
}
i++;
pos = 0;
while (save[i])
str[pos++] = save[i++];
str[pos] = '\0';
free(save);
return (str);
}
char *ft_read_save(int fd, char *save)
{
char *buff;
int num_bytes;
buff = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buff)
return (NULL);
num_bytes = 1;
while (!ft_strchr(save, '\n') && num_bytes != 0)
{
num_bytes = read(fd, buff, BUFFER_SIZE);
if (num_bytes == -1)
{
free(buff);
free(save);
return (NULL);
}
buff[num_bytes] = '\0';
save = ft_strjoin(save, buff);
}
free(buff);
return (save);
}
char *get_next_line(int fd)
{
char *line;
static char *save;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
save = ft_read_save(fd, save);
if (!save)
return (NULL);
line = ft_line(save);
save = ft_save(save);
return (line);
}