-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
77 lines (69 loc) · 1.93 KB
/
get_next_line.c
File metadata and controls
77 lines (69 loc) · 1.93 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcherki <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/01/07 17:29:35 by mcherki #+# #+# */
/* Updated: 2022/01/07 17:48:35 by mcherki ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_line(char *str)
{
int i;
i = 0;
while (str[i] != '\n')
i++;
return (ft_substr(str, 0, i + 1));
}
char *get_rest(char *str)
{
int i;
char *ptr;
i = 0;
while (str[i] != '\n')
i++;
ptr = ft_substr(str, i + 1, ft_strlen(str) - i);
free(str);
return (ptr);
}
int newline(char *str)
{
if (!str)
return (0);
while (*str != '\0')
{
if (*str == '\n')
return (1);
str++;
}
return (0);
}
char *get_next_line(int fd)
{
int k;
char *line;
static char *rest;
char *buff;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buff = malloc(BUFFER_SIZE + 1);
if (!buff)
return (NULL);
if (newline(rest))
return (line = get_line(rest), rest = get_rest(rest), free(buff), line);
k = read(fd, buff, BUFFER_SIZE);
if (k <= 0)
{
if (!rest)
return (free(buff), NULL);
if (!*rest)
return (free(buff), free(rest), rest = NULL, NULL);
line = ft_strdup(rest);
return (free(rest), free(buff), rest = NULL, line);
}
buff[k] = '\0';
return (rest = ft_strjoin(rest, buff), free(buff), get_next_line(fd));
}