-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
99 lines (90 loc) · 2.42 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
93
94
95
96
97
98
99
/* ************************************************************************** */
/* */
/* :::::::: */
/* get_next_line.c :+: :+: */
/* +:+ */
/* By: dreijans <[email protected]> +#+ */
/* +#+ */
/* Created: 2023/01/09 11:35:31 by dreijans #+# #+# */
/* Updated: 2023/01/18 18:18:37 by dreijans ######## odam.nl */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
ssize_t ft_find_newline(char *str)
{
int i;
i = 0;
if (!str)
return (0);
while (str[i])
{
if (str[i] == '\n')
return (i);
i++;
}
return (-1);
}
char *ft_read_line(int fd, char *buffer, char *read_buffer)
{
int byte_read;
char *free_string;
while (ft_find_newline(read_buffer) == -1)
{
if (buffer == NULL)
return (buffer);
byte_read = read (fd, read_buffer, BUFFER_SIZE);
read_buffer[byte_read] = '\0';
if (byte_read == 0)
return (buffer);
if (byte_read == -1)
{
read_buffer[0] = '\0';
free (buffer);
return (0);
}
free_string = buffer;
buffer = ft_copy_join(buffer, read_buffer);
free (free_string);
if (buffer == NULL)
return (NULL);
}
return (buffer);
}
char *ft_save(char *str)
{
char *new_str;
int len;
new_str = NULL;
len = ft_find_newline(str);
if (len == -1)
return (str);
new_str = ft_substr(str, 0, len + 1);
free (str);
return (new_str);
}
char *get_next_line(int fd)
{
static char read_buffer[BUFFER_SIZE + 1];
char *buffer;
int i;
buffer = NULL;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buffer = ft_copy_join(buffer, read_buffer);
if (buffer == NULL)
return (NULL);
buffer = ft_read_line(fd, buffer, read_buffer);
if (buffer == NULL)
return (NULL);
buffer = ft_save(buffer);
if (buffer == NULL)
return (NULL);
i = ft_find_newline(read_buffer);
ft_strlcpy(read_buffer, &read_buffer[i + 1], ft_strlen(&read_buffer[i]));
if (read_buffer[0] == '\0' && buffer[0] == '\0')
{
free (buffer);
return (NULL);
}
return (buffer);
}