-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_next_line.c
108 lines (98 loc) · 2.42 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gmacias- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/24 18:29:29 by gmacias- #+# #+# */
/* Updated: 2023/05/18 16:58:40 by gmacias- ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_free_strjoin(char *save, char *tmp)
{
char *new;
new = ft_strjoin(save, tmp);
free(save);
return (new);
}
char *the_rest(char *save)
{
int i;
int n;
char *new_save;
i = 0;
while (save[i] != '\0' && save[i] != '\n')
i++;
if (save[i] == '\0')
{
free(save);
return (NULL);
}
new_save = ft_calloc(sizeof(char), (ft_strlen(save) - i + 1));
i++;
n = 0;
while (save[i] != '\0')
new_save[n++] = save[i++];
free(save);
return (new_save);
}
char *make_line_from(char *save)
{
int i;
char *line;
i = 0;
if (save[i] == '\0')
return (NULL);
while (save[i] != '\0' && save[i] != '\n')
i++;
line = ft_calloc(sizeof(char), (i + 2));
i = 0;
while (save[i] != '\0' && save[i] != '\n')
{
line[i] = save[i];
i++;
}
if (save[i] == '\n')
line[i] = '\n';
return (line);
}
char *read_until_enter(int fd, char *save)
{
int n_of_chars;
char *tmp;
if (!save)
save = ft_calloc(1, 1);
tmp = ft_calloc(sizeof(char), BUFFER_SIZE + 1);
n_of_chars = 1;
while (n_of_chars > 0)
{
n_of_chars = read(fd, tmp, BUFFER_SIZE);
if (n_of_chars == -1)
{
free(tmp);
free(save);
return (NULL);
}
tmp[n_of_chars] = '\0';
save = ft_free_strjoin(save, tmp);
if (ft_strchr(save, '\n'))
break ;
}
free(tmp);
return (save);
}
char *get_next_line(int fd)
{
char *line;
static char *save;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
save = read_until_enter(fd, save);
if (save == NULL)
return (NULL);
line = make_line_from(save);
save = the_rest(save);
return (line);
}