-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
151 lines (138 loc) · 2.96 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/* ************************************************************************** */
/* */
/* :::::::: */
/* get_next_line.c :+: :+: */
/* +:+ */
/* By: nvan-der <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/01/17 18:45:01 by nvan-der #+# #+# */
/* Updated: 2021/05/17 11:30:35 by nvan-der ######## odam.nl */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <fcntl.h>
#include <stdio.h>
#include <limits.h>
char *ft_strchr(char *s, int c)
{
size_t i;
char *ret;
i = 0;
if (s == NULL)
return (NULL);
while (s[i] != '\0')
{
if (s[i] == c)
{
ret = ft_strdup(s + i + 1);
if (ret == NULL)
{
free(s);
return (0);
}
free(s);
return (ret);
}
i++;
}
return (0);
}
int ft_check_fd(char *s)
{
int i;
i = 0;
if (s == NULL)
return (0);
while (s[i] != '\0')
{
if (s[i] == '\n')
return (1);
i++;
}
return (0);
}
char *ft_read_fd(char **temp, int fd, ssize_t ret)
{
char *buf;
while (ret > 0)
{
buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (buf == NULL)
{
free(temp[fd]);
return (NULL);
}
ret = read(fd, buf, BUFFER_SIZE);
if (ret < 0)
{
free(buf);
free(temp[fd]);
return (NULL);
}
buf[ret] = '\0';
temp[fd] = ft_strjoin(temp[fd], buf);
if (temp[fd] == NULL)
return (NULL);
if (ft_check_fd(temp[fd]))
break ;
}
return (temp[fd]);
}
int ft_make_line(char **temp, char **line, int fd)
{
int i;
i = 0;
while (temp[fd][i] != '\n' && temp[fd][i] != '\0')
i++;
if (temp[fd][i] == '\n')
{
*line = ft_substr(temp[fd]);
if (*line == NULL)
{
free(temp[fd]);
return (-1);
}
temp[fd] = ft_strchr(temp[fd], '\n');
if (temp[fd] == NULL)
return (-1);
return (1);
}
*line = ft_strdup(temp[fd]);
free(temp[fd]);
if (*line == NULL)
return (-1);
temp[fd] = 0;
return (0);
}
int get_next_line(int fd, char **line)
{
ssize_t ret;
static char *temp[INT_MAX];
ret = 1;
if (fd < 0 || !line || BUFFER_SIZE <= 0 || fd > OPEN_MAX)
return (-1);
if (temp[fd] == NULL)
temp[fd] = ft_strdup("");
if (temp[fd] == NULL)
return (-1);
temp[fd] = ft_read_fd(temp, fd, ret);
if (temp[fd] == NULL)
return (-1);
return (ft_make_line(temp, line, fd));
}
// TEST FUNCTION
// int main(void)
// {
// char *line;
// int fd;
// line = "";
// fd = open("test.txt", O_RDONLY);
// int i = 1;
// while (i > 0)
// {
// i = get_next_line(fd, &line);
// printf("%d = ", i);
// printf("%s\n", line);
// free(line);
// }
// }