-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
79 lines (71 loc) · 1.46 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
#include "get_next_line.h"
char *read_file(int fd, char *stash)
{
char buf[BUFFER_SIZE];
int nread;
int i;
nread = 1;
i = 0;
while (i < BUFFER_SIZE)
{
buf[i] = '\0';
i++;
}
while (nread && !(ft_strchr(buf, '\n')))
{
nread = read(fd, buf, BUFFER_SIZE);
if (nread == -1)
return (free(stash), NULL);
buf[nread] = '\0';
stash = ft_strjoin(stash, buf);
if (!stash)
return (NULL);
}
return (stash);
}
char *extract_line(char *stash)
{
char *line;
int i;
i = 0;
line = NULL;
if (stash[i] == '\0')
return (NULL);
while (stash[i] && stash[i] != '\n')
i++;
line = ft_substr(stash, 0, i + 1);
if (!line)
return (NULL);
return (line);
}
char *clean_stash(char *stash)
{
char *tmp;
int i;
tmp = NULL;
i = 0;
while (stash[i] && stash[i] != '\n')
i++;
if (stash[i] == '\0')
return (free(stash), NULL);
tmp = ft_substr(stash, i + 1, ft_strlen(stash));
if (!tmp)
return (NULL);
free(stash);
return (tmp);
}
char *get_next_line(int fd)
{
static char *stash;
char *line;
if (fd < 0 || BUFFER_SIZE < 1)
return (NULL);
stash = read_file(fd, stash);
if (!stash)
return (NULL);
line = extract_line(stash);
if (!line)
return (free(stash), NULL);
stash = clean_stash(stash);
return (line);
}