-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
101 lines (89 loc) · 2.54 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ttavares <ttavares@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/23 16:08:33 by ttavares #+# #+# */
/* Updated: 2022/11/29 11:29:03 by ttavares ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
/* Formats stash to remove previous recovered line, keeping
only the necessary excess after \n for next get_next_line call */
char *format_stash(char *stash)
{
int i;
int stashlenght;
char *formatedstash;
i = 0;
while (stash[i] && stash[i] != '\n')
i++;
if (!stash[i])
{
free (stash);
return (0);
}
stashlenght = ft_strlen(stash);
formatedstash = malloc (sizeof(char) * (stashlenght - i + 1));
if (!formatedstash)
return (0);
i++;
ft_strlcpy(formatedstash, stash + i, stashlenght - i + 1);
free (stash);
return (formatedstash);
}
/* Retrieves a formated line from the stashed buffer*/
char *format_line(char *stash)
{
int i;
char *formatedline;
i = 0;
if (!stash[i])
return (0);
while (stash[i] && stash[i] != '\n')
i++;
i++;
formatedline = malloc (sizeof(char) * (i + 1));
if (!formatedline)
return (0);
ft_strlcpy(formatedline, stash, i + 1);
return (formatedline);
}
/*Reads and stashes function in static var while no new line is found*/
char *read_stash(int fd, char *stash)
{
char *buffer;
int bytesread;
bytesread = 1;
buffer = malloc (sizeof(char) * (BUFFER_SIZE + 1));
if (!buffer)
return (0);
while (find_linebreaker(stash) == 0 && bytesread != 0)
{
bytesread = read(fd, buffer, BUFFER_SIZE);
if (bytesread == -1)
{
free(buffer);
return (0);
}
buffer[bytesread] = '\0';
stash = ft_strjoin(stash, buffer);
}
free(buffer);
return (stash);
}
char *get_next_line(int fd)
{
static char *stash;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
stash = read_stash(fd, stash);
if (!stash)
return (0);
line = format_line(stash);
stash = format_stash(stash);
return (line);
}