-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
90 lines (83 loc) · 2.13 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmoumni <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/14 19:58:59 by mmoumni #+# #+# */
/* Updated: 2022/01/02 17:10:00 by mmoumni ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *read_line(char *static_buff, int fd)
{
char *buffer;
int n;
buffer = malloc(BUFFER_SIZE + 1);
if (!buffer)
return (NULL);
n = 1;
while (n > 0 && get_ft_strchr(static_buff, '\n') == NULL)
{
n = read(fd, buffer, BUFFER_SIZE);
if (n == -1)
{
free(buffer);
return (NULL);
}
buffer[n] = '\0';
if (n == 0)
break ;
static_buff = get_ft_strjoin(static_buff, buffer);
}
free(buffer);
return (static_buff);
}
char *backup_func(char *backup)
{
char *dest;
int len;
int i;
len = 0;
i = 0;
while (backup[len] != '\n' && backup[len] != '\0')
len++;
if (backup[len] == '\0')
{
free(backup);
return (NULL);
}
dest = get_ft_strdup(backup + len + 1);
free(backup);
if (dest[0] == '\0')
{
free(dest);
return (NULL);
}
return (dest);
}
char *get_next_line(int fd)
{
static char *backup;
char *line;
int i;
int len;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
backup = read_line(backup, fd);
if (backup == NULL)
return (NULL);
i = -1;
len = 0;
while (backup[len] != '\n' && backup[len] != '\0')
len++;
line = malloc(sizeof(char) * (len + 1));
if (!line)
return (NULL);
while (++i < len)
line[i] = backup[i];
line[i] = '\0';
backup = backup_func(backup);
return (line);
}