-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
128 lines (117 loc) · 2.72 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vmustone <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/23 16:58:47 by vmustone #+# #+# */
/* Updated: 2022/12/08 15:54:53 by vmustone ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *join(char *stash, char *buf)
{
char *temp;
temp = ft_strjoin(stash, buf);
free(stash);
return (temp);
}
static char *after_newline(char *stash, int *error)
{
int i;
int j;
char *end_line;
i = 0;
j = 0;
while (stash[i] && stash[i] != '\n')
i++;
if (!stash[i])
{
free(stash);
return (NULL);
}
end_line = (char *)malloc(sizeof(char) * (ft_strlen(stash) - i + 1));
if (!end_line)
{
*error = 1;
return (NULL);
}
i++;
while (stash[i])
end_line[j++] = stash[i++];
free(stash);
end_line[j] = '\0';
return (end_line);
}
static char *find_newline(char *stash)
{
int i;
char *line_ret;
i = 0;
if (!stash[i])
return (NULL);
while (stash[i] && stash[i] != '\n')
i++;
line_ret = (char *)malloc(sizeof(char) * (i + 2));
if (!line_ret)
return (NULL);
i = 0;
while (stash[i] && stash[i] != '\n')
{
line_ret[i] = stash[i];
i++;
}
if (stash[i] && stash[i] == '\n')
line_ret[i++] = '\n';
line_ret[i] = '\0';
return (line_ret);
}
static char *read_and_stash(int fd, char *ret)
{
int bytes_read;
char *buf;
buf = (char *)malloc(sizeof(char) * BUFFER_SIZE + 1);
if (!buf)
return (NULL);
bytes_read = 1;
while (bytes_read > 0 && !ft_strchr(ret, '\n'))
{
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read == -1)
{
free(buf);
return (NULL);
}
buf[bytes_read] = 0;
ret = join(ret, buf);
if (!ret)
return (NULL);
}
free(buf);
return (ret);
}
char *get_next_line(int fd)
{
static char *stash;
char *line;
int error;
error = 0;
if (fd < 0 || fd > 4096 || read(fd, 0, 0) < 0)
return (NULL);
if (!stash)
stash = ft_calloc(1, 1);
if (!stash)
return (NULL);
stash = read_and_stash(fd, stash);
if (!stash)
return (NULL);
line = find_newline(stash);
stash = after_newline(stash, &error);
if (error)
{
free(line);
return (NULL);
}
return (line);
}