-
Notifications
You must be signed in to change notification settings - Fork 7
/
get_next_line.c
127 lines (116 loc) · 2.81 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jdecorte <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/19 11:09:06 by jdecorte #+# #+# */
/* Updated: 2021/11/08 23:14:55 by jdecorte ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
// join and free
char *ft_free(char *buffer, char *buf)
{
char *temp;
temp = ft_strjoin(buffer, buf);
free(buffer);
return (temp);
}
// delete line find
char *ft_next(char *buffer)
{
int i;
int j;
char *line;
i = 0;
// find len of first line
while (buffer[i] && buffer[i] != '\n')
i++;
// if eol == \0 return NULL
if (!buffer[i])
{
free(buffer);
return (NULL);
}
// len of file - len of firstline + 1
line = ft_calloc((ft_strlen(buffer) - i + 1), sizeof(char));
i++;
j = 0;
// line == buffer
while (buffer[i])
line[j++] = buffer[i++];
free(buffer);
return (line);
}
// take line for return
char *ft_line(char *buffer)
{
char *line;
int i;
i = 0;
// if no line return NULL
if (!buffer[i])
return (NULL);
// go to the eol
while (buffer[i] && buffer[i] != '\n')
i++;
// malloc to eol
line = ft_calloc(i + 2, sizeof(char));
i = 0;
// line = buffer
while (buffer[i] && buffer[i] != '\n')
{
line[i] = buffer[i];
i++;
}
// if eol is \0 or \n, replace eol by \n
if (buffer[i] && buffer[i] == '\n')
line[i++] = '\n';
return (line);
}
char *read_file(int fd, char *res)
{
char *buffer;
int byte_read;
// malloc if res dont exist
if (!res)
res = ft_calloc(1, 1);
// malloc buffer
buffer = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
byte_read = 1;
while (byte_read > 0)
{
// while not eof read
byte_read = read(fd, buffer, BUFFER_SIZE);
if (byte_read == -1)
{
free(buffer);
return (NULL);
}
// 0 to end for leak
buffer[byte_read] = 0;
// join and free
res = ft_free(res, buffer);
// quit if \n find
if (ft_strchr(buffer, '\n'))
break ;
}
free(buffer);
return (res);
}
char *get_next_line(int fd)
{
static char *buffer;
char *line;
// error handling
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
buffer = read_file(fd, buffer);
if (!buffer)
return (NULL);
line = ft_line(buffer);
buffer = ft_next(buffer);
return (line);
}