-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
82 lines (73 loc) · 1.16 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
/*
** EPITECH PROJECT, 2017
** CPE_getnextline_2017
** File description:
** gnl
*/
#include <stdlib.h>
#include <unistd.h>
#include "get_next_line.h"
void my_memset(void *dst,
int val,
size_t size)
{
char *p;
if (dst == NULL)
return;
p = (char *)dst;
while (size > 0)
{
*p++ = (char)val;
--size;
}
}
char *xrealloc(char *p, size_t size)
{
char *ret;
size_t c;
ret = (char*)malloc(size);
if (ret == NULL)
return (NULL);
my_memset(ret, 0, size);
if (p != NULL)
{
c = 0;
while (p[c])
{
ret[c] = p[c];
c++;
}
free(p);
}
return (ret);
}
inline int read_more(const int *fd,
char *buffer)
{
int ret;
my_memset(buffer, 0, READ_SIZE + 1);
ret = read((*fd), buffer, READ_SIZE);
return (ret);
}
char *get_next_line(int fd)
{
static char buffer[READ_SIZE + 1];
static int j;
register int i = 0;
char *line = NULL;
while (fd >= 0)
{
if (!buffer[j])
j ^= j;
if (!j && (read_more(&fd, buffer) < 1))
return (line);
if ((!line || !j) &&
!(line =
xrealloc(line, READ_SIZE + i + 1)))
return (0);
if ((buffer[j] == '\n') && (++j))
return (line);
line[i++] = buffer[j++];
}
return (0);
}