-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
92 lines (82 loc) · 2.01 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abouchfa <abouchfa@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/13 19:25:08 by abouchfa #+# #+# */
/* Updated: 2021/11/17 13:51:16 by abouchfa ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
void ft_free(void *p)
{
if (p)
free(p);
}
void reset_buffer(char *buffer)
{
size_t l;
size_t i;
l = 0;
i = 0;
while (buffer[l] != '\n' && buffer[l] != '\0')
l++;
while (buffer[l++])
buffer[i++] = buffer[l];
buffer[i] = 0;
}
char *collect_line(char *line)
{
int len;
char *temp;
if (!*line)
{
ft_free(line);
return (NULL);
}
len = 0;
while (*(line + len) != '\n' && *(line + len) != '\0')
len++;
if (*(line + len) == '\n')
len++;
temp = line;
line = malloc (len + 1);
ft_strncpy(line, temp, len);
ft_free(temp);
return (line);
}
char *read_line(int fd, char *buffer)
{
char *temp;
char *line;
int res;
res = 1;
line = NULL;
if (*buffer)
{
line = "\0";
line = ft_strjoin(line, buffer);
}
while (!gnl_strchr(line) && res > 0)
{
res = read(fd, buffer, BUFFER_SIZE);
buffer[res] = 0;
temp = line;
if (!line)
line = "\0";
line = ft_strjoin(line, buffer);
ft_free(temp);
}
return (line);
}
char *get_next_line(int fd)
{
static char buffer[BUFFER_SIZE + 1];
char *line;
line = read_line(fd, buffer);
line = collect_line(line);
reset_buffer(buffer);
return (line);
}