-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
99 lines (90 loc) · 2.5 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: gantonio <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/20 21:41:34 by gantonio #+# #+# */
/* Updated: 2021/06/22 23:28:41 by gantonio ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <stdio.h>
char *ft_fix_repository(char *str)
{
char *repo;
int len;
int i;
len = 0;
i = 0;
if (!str)
return (NULL);
while (str[len] && str[len] != '\n')
len++;
if (!str[len])
{
free(str);
return (NULL);
}
repo = malloc(sizeof(char) * ((ft_strlen(str) - len) + 1));
if (!repo)
return (0);
while (str[++len])
repo[i++] = str[len];
repo[i] = '\0';
free(str);
return (repo);
}
static char *ft_return_new_line(char *str)
{
int len;
char *new_line;
len = 0;
if (!str)
return (NULL);
while (str[len] && str[len] != '\n')
len++;
new_line = malloc(sizeof(char) * (len + 1));
if (!new_line)
return (NULL);
len = -1;
while (str[++len] && str[len] != '\n')
new_line[len] = str[len];
new_line[len] = '\0';
return (new_line);
}
static int ft_read_and_join(int fd, char **repository, char *buf)
{
int bytes_read;
bytes_read = 1;
while (!ft_is_new_line(*repository) && bytes_read > 0)
{
bytes_read = read(fd, buf, BUFFER_SIZE);
if (bytes_read == -1)
return (GNL_ERROR);
buf[bytes_read] = '\0';
*repository = ft_strjoin(*repository, buf);
}
return (bytes_read);
}
int get_next_line(int fd, char **line)
{
char *buf;
int bytes_read;
static char *repository;
if (fd < 0 || !line || BUFFER_SIZE <= 0)
return (GNL_ERROR);
buf = malloc(sizeof(char) * BUFFER_SIZE + 1);
if (!buf)
return (GNL_ERROR);
bytes_read = ft_read_and_join(fd, &repository, buf);
free(buf);
if (bytes_read == -1)
return (GNL_ERROR);
*line = ft_return_new_line(repository);
repository = ft_fix_repository(repository);
if (bytes_read == 0)
return (GNL_EOF);
return (GNL_LINEBREAK);
}