-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_next_line.c
More file actions
126 lines (115 loc) · 2.6 KB
/
Copy pathget_next_line.c
File metadata and controls
126 lines (115 loc) · 2.6 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
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
121
122
123
124
125
126
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erico-ke <erico-ke@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/12 15:16:51 by erico-ke #+# #+# */
/* Updated: 2024/11/29 14:54:16 by erico-ke ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *ft_get_read(int fd, char *backup)
{
int check_read;
char *buf;
buf = ft_calloc(sizeof(char), (BUFFER_SIZE + 1));
if (!buf)
return (NULL);
check_read = 1;
while (!(ft_strchr(backup, '\n')) && check_read != 0)
{
check_read = read(fd, buf, BUFFER_SIZE);
if (check_read < 0)
{
free(buf);
free(backup);
return (NULL);
}
buf[check_read] = 0;
backup = ft_strjoin(backup, buf);
}
free(buf);
return (backup);
}
static char *ft_get_line(char *backup)
{
int i;
char *line;
i = 0;
if (backup[0] == 0)
return (NULL);
while (backup[i] && (backup[i] != '\n'))
i++;
line = ft_calloc(sizeof(char), (i + 2));
if (!line)
return (NULL);
i = 0;
while (backup[i] && (backup[i] != '\n'))
{
line[i] = backup[i];
i++;
}
if (backup[i] == '\n')
{
line[i] = backup[i];
i++;
}
line[i] = '\0';
return (line);
}
static char *ft_get_rest(char *backup)
{
int i;
int rest_i;
char *rest;
i = 0;
while (backup[i] && (backup[i] != '\n'))
i++;
if (!backup[i])
{
free(backup);
return (NULL);
}
rest = malloc(sizeof(char) * (ft_strlen(backup) - i + 1));
if (!rest)
{
free(rest);
return (NULL);
}
++i;
rest_i = 0;
while (backup[i])
rest[rest_i++] = backup[i++];
rest[rest_i] = '\0';
free(backup);
return (rest);
}
char *get_next_line(int fd)
{
char *line;
static char *backup;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
backup = ft_get_read(fd, backup);
if (!backup)
return (NULL);
line = ft_get_line(backup);
backup = ft_get_rest(backup);
return (line);
}
/* int main()
{
int fd = open("only_nl.txt", O_RDONLY);
char *r;
r = get_next_line(fd);
while (r)
{
free(r);
r = get_next_line(fd);
printf("%s", r);
}
close(fd);
return 0;
} */