-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
124 lines (114 loc) · 2.52 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
121
122
123
124
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: whendrix <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/28 23:57:23 by whendrix #+# #+# */
/* Updated: 2022/08/02 20:52:52 by whendrix ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_get_line(char *buffer)
{
int i;
char *str;
i = 0;
if (!buffer[i])
return (NULL);
while (buffer[i] && buffer[i] != '\n')
i++;
str = ft_substr(buffer, 0, i + ft_endl(buffer));
if (!str)
{
free(str);
return (NULL);
}
return (str);
}
char *ft_new_str(char *buffer)
{
int i;
int j;
char *str;
i = 0;
while (buffer[i] && buffer[i] != '\n')
i++;
if (!buffer[i])
{
free(buffer);
return (NULL);
}
str = malloc(sizeof(char) * (ft_strlen(buffer) - i + 1));
if (!str)
{
free(str);
return (NULL);
}
i++;
j = 0;
while (buffer[i])
str[j++] = buffer[i++];
str[j] = '\0';
free(buffer);
return (str);
}
char *ft_read_str(int fd, char *buffer)
{
char *s;
int bytes;
s = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!s)
return (NULL);
bytes = 1;
while (!ft_strchr(buffer, '\n') && bytes != 0)
{
bytes = read(fd, s, BUFFER_SIZE);
if (bytes < 0)
{
free(s);
return (NULL);
}
s[bytes] = '\0';
buffer = ft_strjoin(buffer, s);
}
free(s);
return (buffer);
}
char *get_next_line(int fd)
{
char *line;
static char *buffer;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
buffer = ft_read_str(fd, buffer);
if (!buffer)
return (NULL);
line = ft_get_line(buffer);
buffer = ft_new_str(buffer);
return (line);
}
/*int main(void)
{
char *line;
int i;
int fd;
fd = open("file1.txt", O_RDONLY);
i = 1;
while (i < 7)
{
line = get_next_line(fd);
printf("line [%02d]: %s", i, line);
free(line);
i++;
}
if (i == -1)
{
printf("<ERROR>\n");
close(fd);
return (-1);
}
close(fd);
return (0);
}*/