-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
112 lines (101 loc) · 2.35 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: waraissi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/13 19:34:50 by waraissi #+# #+# */
/* Updated: 2022/11/17 18:20:01 by waraissi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int get_index(char *str)
{
int i;
i = 0;
if (!str)
return (0);
while (str[i] && str[i] != '\n')
i++;
if (str[i] == '\n')
i++;
return (i);
}
char *before_newline(char *str)
{
int i;
char *p;
i = 0;
if (!str[i])
return (NULL);
p = malloc(sizeof(char) * get_index(str) + 1);
if (!p)
return (NULL);
while (str[i] && str[i] != '\n')
{
p[i] = str[i];
i++;
}
if (str[i] == '\n')
p[i++] = '\n';
p[i] = 0;
return (p);
}
char *after_newline(char *str)
{
int i;
size_t j;
char *s;
i = 0;
j = get_index(str);
if (j == ft_strlen(str))
return (free(str), NULL);
s = malloc(ft_strlen(str) - j + 1);
if (!s)
return (NULL);
while (str[j])
s[i++] = str[j++];
s[i] = '\0';
return (free(str), str = NULL, s);
}
int is_newline(char *str)
{
int i;
i = 0;
if (!str)
return (0);
while (str[i])
{
if (str[i] == '\n')
return (1);
i++;
}
return (0);
}
char *get_next_line(int fd)
{
static char *backup;
char *buffer;
char *line;
ssize_t i;
i = 1;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
if (!backup)
backup = ft_strdup("");
buffer = malloc(sizeof(char) * BUFFER_SIZE + 1);
if (!buffer)
return (NULL);
while (i && is_newline(backup) == 0)
{
i = read(fd, buffer, BUFFER_SIZE);
if (i == -1)
return (free(backup), free(buffer), backup = NULL, NULL);
buffer[i] = '\0';
backup = ft_strjoin(backup, buffer);
}
line = before_newline(backup);
backup = after_newline(backup);
return (free(buffer), line);
}