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
|
/*
ft_getline Copyright (C) 2026 yctct
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "ft_getline.h"
char *read_file(int fd, char *buf, char *line, char *stash)
{
ssize_t bytes_read;
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read < 0)
{
free(line);
return (NULL);
}
buf[bytes_read] = 0;
if (bytes_read == 0)
{
if (line[0] != 0)
{
stash[0] = 0;
return (line);
}
else
{
free(line);
return (NULL);
}
}
return (buf);
}
char *eol_is_in_line(char *pivot, char *stash, char *line)
{
int i;
int j;
char *tmp;
i = 1;
j = 0;
while (pivot[i] != 0)
stash[j++] = pivot[i++];
stash[j] = 0;
pivot[1] = 0;
tmp = line;
line = ft_strdup(line);
free(tmp);
return (line);
}
char *keep_reading(int fd, char *pivot, char *stash, char *line)
{
char buf[BUFFER_SIZE + 1];
while (read_file(fd, buf, line, stash) != 0)
{
line = ft_strjoin(line, buf);
if (!line)
return (NULL);
pivot = ft_strchr(line, EOL);
if (pivot != 0)
return (eol_is_in_line(pivot, stash, line));
else if (buf[0] == 0)
return (line);
}
return (NULL);
}
char *ft_getline(int fd)
{
char *line;
static char stash[BUFFER_SIZE] = "\0";
char *pivot;
if ((fd < -1) || (fd > 1024))
return (NULL);
line = ft_strdup(stash);
if (!line)
return (NULL);
pivot = ft_strchr(line, EOL);
if (pivot != 0)
return (eol_is_in_line(pivot, stash, line));
else
return (keep_reading(fd, pivot, stash, line));
return (NULL);
}
|