-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
109 lines (100 loc) · 2.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dalves-p <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/11 13:35:15 by dalves-p #+# #+# */
/* Updated: 2021/06/28 16:06:07 by dalves-p ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
int is_line(char *backup)
{
int i;
i = 0;
if (!backup)
return (0);
while (backup[i])
{
if (backup[i] == '\n')
return (1);
i++;
}
return (0);
}
static char *get_line(char *backup)
{
int i;
char *line;
i = 0;
if (!backup)
return (0);
while (backup[i] != '\n' && backup[i] != '\0')
i++;
line = malloc((i + 1) * sizeof(char));
if (!line)
return (0);
i = 0;
while (backup[i] != '\n' && backup[i] != '\0')
{
line[i] = backup[i];
i++;
}
line[i] = '\0';
return (line);
}
static char *get_backup(char *backup)
{
int i;
int j;
char *newbackup;
i = 0;
j = 0;
if (!backup)
return (0);
while (backup[i] != '\n' && backup[i] != '\0')
i++;
if (backup[i] == 0)
{
free(backup);
return (0);
}
newbackup = malloc((ft_strlen(backup) - i + 1) * sizeof(char));
if (!newbackup)
return (0);
i++;
while (backup[i] != '\0')
newbackup[j++] = backup[i++];
newbackup[j] = '\0';
free(backup);
return (newbackup);
}
int get_next_line(int fd, char **line)
{
static char *backup[OPEN_MAX];
char *buffer;
int buffsize;
if (fd < 0 || BUFFER_SIZE <= 0 || line == 0 || fd > OPEN_MAX)
return (-1);
buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
buffsize = 1;
while (((is_line(backup[fd])) == 0) && (buffsize != 0))
{
buffsize = read(fd, buffer, BUFFER_SIZE);
if (buffsize == -1)
{
free(buffer);
return (-1);
}
buffer[buffsize] = '\0';
backup[fd] = ft_strjoin(backup[fd], buffer);
}
free(buffer);
*line = get_line(backup[fd]);
backup[fd] = get_backup(backup[fd]);
if (buffsize == 0)
return (0);
return (1);
}