-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
94 lines (86 loc) · 1.46 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
#include "get_next_line_bonus.h"
char *ft_get_line(int fd, char *line)
{
char *buffer;
ssize_t read_bytes;
buffer = (char *)malloc(BUFFER_SIZE + 1);
if (!buffer)
return (NULL);
read_bytes = 1;
while (!ft_strchr(line, '\n') && read_bytes > 0)
{
read_bytes = read(fd, buffer, BUFFER_SIZE);
if (read_bytes == -1)
{
free(buffer);
return (NULL);
}
buffer[read_bytes] = '\0';
line = ft_strjoin(line, buffer);
}
free(buffer);
return (line);
}
char *new_line(char *line)
{
int i;
int j;
char *str;
i = 0;
while (line[i] && line[i] != '\n')
i++;
if (!line[i])
{
free(line);
return (NULL);
}
str = (char *)malloc(sizeof(char) * (ft_strlen(line) - i + 1));
if (!str)
return (NULL);
i++;
j = 0;
while (line[i])
str[j++] = line[i++];
str[j] = '\0';
free(line);
return (str);
}
char *ft_get_next_line(char *line)
{
int i;
char *str;
i = 0;
if (!line[i])
return (NULL);
while (line[i] && line[i] != '\n')
i++;
str = (char *)malloc(i + 2);
if (!str)
return (NULL);
i = 0;
while (line[i] && line[i] != '\n')
{
str[i] = line[i];
i++;
}
if (line[i] == '\n')
{
str[i] = line[i];
i++;
}
str[i] = '\0';
return (str);
}
char *get_next_line(int fd)
{
static char *line[OPEN_MAX];
char *next_line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
line[fd] = ft_get_line(fd, line[fd]);
if (!line[fd])
return (NULL);
next_line = ft_get_next_line(line[fd]);
line[fd] = new_line(line[fd]);
return (next_line);
}