-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
120 lines (109 loc) · 2.56 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pveiga-c <pveiga-c@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/18 18:12:47 by pveiga-c #+# #+# */
/* Updated: 2023/05/25 15:25:07 by pveiga-c ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *check(char *stash, int nbits)
{
if (nbits == 0 && *stash == '\0')
{
free(stash);
return (NULL);
}
if (stash == NULL)
{
stash = malloc(1);
if (stash == NULL)
return (NULL);
*stash = '\0';
}
return (stash);
}
char *ft_read_line(int fd, char *stash)
{
int nbits;
char *buff;
buff = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buff)
return (NULL);
nbits = 1;
while (!ft_strchr(stash, '\n') && nbits > 0)
{
nbits = read(fd, buff, BUFFER_SIZE);
if (nbits == -1)
{
free(stash);
free(buff);
return (NULL);
}
buff[nbits] = '\0';
stash = ft_strjoin(stash, buff);
}
stash = check(stash, nbits);
free(buff);
return (stash);
}
char *ft_next_line(char *stash)
{
char *str;
char *str_f;
int nl_pos;
if (!ft_strchr(stash, '\n'))
str_f = stash + (ft_strlen(stash) - 1);
else
str_f = ft_strchr(stash, '\n');
nl_pos = str_f - stash + 1;
str = (char *)malloc(nl_pos + 1);
if (str == NULL)
{
free(stash);
free(str);
return (0);
}
ft_memmove(str, stash, nl_pos);
str[nl_pos] = '\0';
ft_memmove(stash, nl_pos + stash, ft_strlen(stash) - nl_pos + 1);
return (str);
}
char *get_next_line(int fd)
{
char *line;
static char *stash;
if (fd < 0 && BUFFER_SIZE <= 0)
return (NULL);
stash = ft_read_line(fd, stash);
if (!stash)
return (NULL);
line = ft_next_line(stash);
return (line);
}
/*
# include <stdio.h>
int main(void)
{
int fd;
char *line;
fd = open("testes/test1.txt", O_RDONLY);
if (fd == -1)
{
printf("Failed to open file.\n");
return (1);
}
line = get_next_line(fd);
while (line != NULL)
{
printf("%s", line);
free(line);
line = get_next_line(fd);
}
close(fd);
return (0);
}
*/