-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
executable file
·92 lines (83 loc) · 2.34 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: troberts <troberts@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/23 21:01:35 by troberts #+# #+# */
/* Updated: 2022/06/26 03:08:24 by troberts ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static size_t get_len_of_line(char *buffer)
{
size_t len;
len = 0;
while (buffer[len] != '\n' && buffer[len] != '\0')
len++;
if (buffer[len] == '\n')
len++;
return (len);
}
static ssize_t get_read(int fd, char *buffer)
{
ssize_t len_read;
len_read = read(fd, buffer, BUFFER_SIZE);
if (len_read > 0)
buffer[len_read] = 0;
else
buffer[0] = 0;
return (len_read);
}
static char *get_line(char *buffer, int fd, int *nl_found)
{
ssize_t len_read;
char *line;
size_t len_line;
char *buff_tmp;
if (ft_strlen(buffer) == 0)
{
len_read = get_read(fd, buffer);
if (len_read <= 0)
return (NULL);
}
len_line = get_len_of_line(buffer);
if (buffer[len_line - 1] == '\n')
*nl_found = 1;
line = malloc(len_line + 1);
if (line == NULL)
return (NULL);
ft_strlcpy(line, buffer, len_line + 1);
buff_tmp = ft_strdup((buffer) + len_line);
if (buff_tmp == NULL)
return (NULL);
ft_strlcpy(buffer, buff_tmp, ft_strlen(buff_tmp) + 1);
free(buff_tmp);
return (line);
}
char *get_next_line(int fd)
{
static char buffer[BUFFER_SIZE + 1];
char *line_old;
int nl_found;
char *line;
char *new_line;
if (fd < 0)
return (NULL);
nl_found = 0;
line = get_line(buffer, fd, &nl_found);
if (line == NULL)
return (NULL);
while (nl_found == 0)
{
new_line = get_line(buffer, fd, &nl_found);
if (new_line == NULL)
return (line);
line_old = line;
line = ft_strjoin(line, new_line);
free(new_line);
free(line_old);
}
return (line);
}