-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
115 lines (106 loc) · 2.59 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
107
108
109
110
111
112
113
114
115
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yogun <yogun@student.42heilbronn.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/11 15:01:18 by yogun #+# #+# */
/* Updated: 2022/04/11 15:12:46 by yogun ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *get_next_line(int fd)
{
static char *full_str[666];
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
full_str[fd] = read_function(fd, full_str[fd]);
if (!full_str[fd])
return (NULL);
line = ft_getline(full_str[fd]);
full_str[fd] = ft_getrest(full_str[fd]);
return (line);
}
/**
* read the first line of a file descriptor
*/
char *read_function(int fd, char *str)
{
char *tmp;
int bytes;
tmp = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!tmp)
return (NULL);
bytes = 1;
while (!ft_strchr(str, '\n') && (bytes != 0))
{
bytes = read(fd, tmp, BUFFER_SIZE);
if (bytes == -1)
{
free(tmp);
return (NULL);
}
tmp[bytes] = '\0';
str = ft_strjoin(str, tmp);
}
free(tmp);
return (str);
}
/**
* from the read string, take the first line and returns it
*/
char *ft_getline(char *full_str)
{
int i;
char *line;
i = 0;
if (!full_str[i])
return (NULL);
while (full_str[i] && full_str[i] != '\n')
i++;
line = (char *)malloc(sizeof(char) * (i + 2));
if (!line)
return (NULL);
i = 0;
while (full_str[i] && full_str[i] != '\n')
{
line[i] = full_str[i];
i++;
}
if (full_str[i] == '\n')
{
line[i] = full_str[i];
i++;
}
line[i] = '\0';
return (line);
}
/**
* from the read string, take the first line and remove it. returns the rest
*/
char *ft_getrest(char *full_str)
{
int i;
int j;
char *restof;
i = 0;
while (full_str[i] && full_str[i] != '\n')
i++;
if (!full_str[i])
{
free(full_str);
return (NULL);
}
restof = (char *)malloc(sizeof(char) * (ft_strlen(full_str) - i + 1));
if (!restof)
return (NULL);
i++;
j = 0;
while (full_str[i])
restof[j++] = full_str[i++];
restof[j] = '\0';
free(full_str);
return (restof);
}