-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
110 lines (99 loc) · 2.02 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
#include "get_next_line_bonus.h"
size_t ft_strlcpy(char *dst, char *src, size_t dstsize)
{
unsigned int i;
unsigned int x;
i = 0;
if (dst == NULL || src == NULL)
return (0);
x = ft_strlen(src);
if (dstsize != 0)
{
while (src[i] != '\0' && i < dstsize - 1)
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
}
return (x);
}
/* condition if len is equal to 0,
it returns the string from start until the end */
char *ft_substr(char *s, unsigned int start, size_t len)
{
char *str;
if (ft_strlen(s) == 0)
return (NULL);
if (start > ft_strlen(s))
{
len = 0;
start = 0;
}
if (start + len > ft_strlen(s) || len == 0)
len = ft_strlen(s) - start;
if (len > ft_strlen(s))
len = ft_strlen(s + start);
str = (char *)malloc(sizeof(char) * (len + 1));
if (str == NULL)
return (NULL);
ft_strlcpy(str, (s + start), len + 1);
return (str);
}
char *ft_read_and_stash(char *stash, int fd, int *nbrc)
{
char *buf;
char *new_stash;
buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (buf == NULL)
return (stash);
*nbrc = read(fd, buf, BUFFER_SIZE);
if (*nbrc == -1)
new_stash = NULL;
else if (*nbrc > 0)
{
buf[*nbrc] = '\0';
new_stash = ft_strjoin(stash, buf);
}
else
{
new_stash = ft_strjoin(stash, "");
}
free(buf);
return (new_stash);
}
char *ft_get_and_free_stash(char **stash, int len, int set_stash_null)
{
char *line;
line = ft_substr(*stash, 0, len);
free(*stash);
if (set_stash_null)
*stash = NULL;
return (line);
}
char *get_next_line(int fd)
{
static char *stash[OPEN_MAX];
int line_len;
int nbrc;
char *old_stash;
nbrc = 0;
while (fd >= 0 && BUFFER_SIZE > 0 && nbrc >= 0)
{
old_stash = stash[fd];
if (ft_strchr(stash[fd], '\n'))
{
line_len = ft_strlen_n(stash[fd]) + 1;
stash[fd] = ft_substr(old_stash, line_len, 0);
return (ft_get_and_free_stash(&old_stash, line_len, 0));
}
else
{
stash[fd] = ft_read_and_stash(old_stash, fd, &nbrc);
free(old_stash);
if (nbrc == 0)
return (ft_get_and_free_stash(&stash[fd], 0, 1));
}
}
return (NULL);
}