-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
117 lines (108 loc) · 2.73 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sky <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/15 23:44:38 by sky #+# #+# */
/* Updated: 2020/08/11 20:35:37 by pfile ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#define BUFFER_SIZE 32000
int set_static(int end, char ****sneak, char *str)
{
int len;
len = 0;
if (str[end + 1])
{
end++;
while (str[end + len])
len++;
if (!(***sneak = (char *)malloc(sizeof(char) * len + 1)))
return (0);
(***sneak)[len] = '\0';
while (len--)
(***sneak)[len] = str[end + len];
}
else
***sneak = NULL;
return (1);
}
char *get_join(char *str, int len, char ***sneak, int **eol)
{
char *join;
int start;
int end;
start = 0;
while (start < len)
{
if (str[start] == '\n')
{
**eol = 1;
end = start;
if (!(join = (char *)malloc(sizeof(char) * start + 1)))
return (NULL);
join[start] = '\0';
while (start--)
join[start] = str[start];
if (!set_static(end, &sneak, str))
return (NULL);
return (join);
}
start++;
}
if (!(join = s_strdup(str)))
return (NULL);
return (join);
}
char *break_str(int fd, char **sneak, int *stat, int *eol)
{
char *str;
char *join;
int len;
if (!(str = (char *)malloc(sizeof(char) * BUFFER_SIZE + 1)))
return (NULL);
len = read(fd, str, BUFFER_SIZE);
if (len < 0)
{
*stat = -1;
free(str);
return (NULL);
}
str[len] = '\0';
if (!(join = get_join(str, len, &sneak, &eol)))
return (NULL);
if (len != BUFFER_SIZE && join && !*eol)
*stat = 1;
free(str);
return (join);
}
int get_next_line(int fd, char **line)
{
int stat;
int eol;
char *join;
static char *sneak;
stat = 0;
eol = 0;
*line = NULL;
if (!line || BUFFER_SIZE < 1)
return (-1);
while (!stat)
{
*line = compare_readed(&eol, &sneak, &line);
if (stat == -1 || eol == 1)
return (stat == -1 ? -1 : 1);
join = break_str(fd, &sneak, &stat, &eol);
if (stat == -1 || !join)
return (-1);
*line = compare_readed(&stat, &join, &line);
if (stat == 1 || stat == -1)
return (stat == 1 ? 0 : -1);
if (eol)
return (1);
}
return (1);
}