-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
100 lines (90 loc) · 2.23 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sbronwyn <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/14 16:34:35 by sbronwyn #+# #+# */
/* Updated: 2021/10/14 20:38:29 by sbronwyn ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *create_buf(int size)
{
char *buf;
int i;
if (size <= 0)
return (0);
buf = malloc((size + 1) * sizeof(*buf));
if (buf != 0)
{
i = -1;
while (++i < size + 1)
buf[i] = '\0';
}
return (buf);
}
static void shift_buf(char *buf, int offset)
{
int i;
i = -1;
if (offset < BUFFER_SIZE)
{
while (++i < (BUFFER_SIZE - offset))
buf[i] = buf[i + offset];
i--;
}
while (++i < BUFFER_SIZE)
buf[i] = '\0';
}
static char *append_buf(char *str, char *buf, int size)
{
char *result;
char *temp;
int i;
if (size <= 0)
return (str);
i = 0;
while (i < size && buf[i] != '\n' && buf[i] != '\0')
i++;
if (++i > size)
i = size;
temp = ft_substr(buf, 0, i);
shift_buf(buf, i);
if (str == 0)
return (temp);
result = ft_strjoin(str, temp);
free(str);
free(temp);
return (result);
}
static int str_has_endl(char *str)
{
if (str == 0)
return (0);
if (str[ft_strlen(str) - 1] == '\n')
return (1);
return (0);
}
char *get_next_line(int fd)
{
static char *buf = 0;
int bytes;
char *str;
str = 0;
if (buf == 0)
buf = create_buf(BUFFER_SIZE);
if (buf == 0)
return (0);
bytes = 1;
while (bytes > 0 && !str_has_endl(str))
{
bytes = BUFFER_SIZE;
if (ft_strlen(buf) == 0)
bytes = read(fd, buf, BUFFER_SIZE);
str = append_buf(str, buf, bytes);
}
free_str_and_buf(&str, &buf);
return (str);
}