-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
106 lines (97 loc) · 2.41 KB
/
get_next_line_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wdelaros <wdelaros@student.42quebec.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/22 08:12:24 by wdelaros #+# #+# */
/* Updated: 2022/12/05 06:51:18 by wdelaros ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *ft_getline(char *str)
{
int i;
char *line;
i = 0;
if (!str || !str[i])
return (NULL);
while (str[i] && str[i] != '\n')
i++;
if (str[i] == '\n')
i++;
line = ft_calloc(i + 1, sizeof(char));
if (!line)
{
line = ft_calloc(1, sizeof(char));
return (line);
}
i = 0;
while (str[i] && str[i] != '\n')
{
line[i] = str[i];
i++;
}
if (str[i] && str[i] == '\n')
line[i] = '\n';
return (line);
}
char *nextline(char *str)
{
int i;
int j;
char *buff;
i = 0;
while (str[i] && str[i] != '\n')
i++;
if (!str[i] || !str)
return (free(str), NULL);
buff = ft_calloc((ft_strlen(str) - i + 1), sizeof(char));
if (!buff)
return (free(str), NULL);
i++;
j = 0;
while (str[i])
buff[j++] = str[i++];
return (free(str), buff);
}
char *readstr(int fd, char *str)
{
char *buff;
int i;
if (!str)
{
str = ft_calloc(1, sizeof(char));
if (!str)
return (NULL);
}
buff = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
if (!buff)
return (free(str), NULL);
i = 1;
while (!(ft_strchr(str, '\n')) && i > 0)
{
i = read(fd, buff, BUFFER_SIZE);
if (i == -1)
return (free(buff), free(str), NULL);
buff[i] = 0;
str = ft_strjoin(str, buff);
if (!str)
return (free(buff), NULL);
}
return (free(buff), str);
}
char *get_next_line(int fd)
{
static char *str[OPEN_MAX];
char *line;
if (BUFFER_SIZE <= 0 || fd < 0 || fd > OPEN_MAX)
return (NULL);
str[fd] = readstr(fd, str[fd]);
if (!str[fd])
return (NULL);
line = ft_getline(str[fd]);
str[fd] = nextline(str[fd]);
return (line);
}