-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_gnl.c
115 lines (105 loc) · 2.54 KB
/
ft_gnl.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_gnl.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dalves-p <dalves-p@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/11 13:35:15 by dalves-p #+# #+# */
/* Updated: 2022/05/26 16:42:20 by dalves-p ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** LIBRARY: NA
** DESCRIPTION:
** The ft_gnl() function reads every line of a file
*/
static int is_line(char *backup)
{
int i;
i = 0;
if (!backup)
return (0);
while (backup[i])
{
if (backup[i] == '\n')
return (1);
i++;
}
return (0);
}
static char *get_line(char *backup)
{
int i;
char *line;
i = 0;
if (!backup)
return (0);
while (backup[i] != '\n' && backup[i] != '\0')
i++;
line = malloc((i + 1) * sizeof(char));
if (!line)
return (0);
i = 0;
while (backup[i] != '\n' && backup[i] != '\0')
{
line[i] = backup[i];
i++;
}
line[i] = '\0';
return (line);
}
static char *get_backup(char *backup)
{
int i;
int j;
char *newbackup;
i = 0;
j = 0;
if (!backup)
return (0);
while (backup[i] != '\n' && backup[i] != '\0')
i++;
if (backup[i] == 0)
{
free(backup);
return (0);
}
newbackup = malloc((ft_strlen(backup) - i + 1) * sizeof(char));
if (!newbackup)
return (0);
i++;
while (backup[i] != '\0')
newbackup[j++] = backup[i++];
newbackup[j] = '\0';
free(backup);
return (newbackup);
}
int ft_gnl(int fd, char **line)
{
static char *backup[OPEN_MAX];
char *buffer;
int buffsize;
if (fd < 0 || BUFFER_SIZE <= 0 || line == 0 || fd > OPEN_MAX)
return (-1);
buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
buffsize = 1;
while (((is_line(backup[fd])) == 0) && (buffsize != 0))
{
buffsize = read(fd, buffer, BUFFER_SIZE);
if (buffsize == -1)
{
free(buffer);
return (-1);
}
buffer[buffsize] = '\0';
backup[fd] = ft_strjoin(backup[fd], buffer);
}
free(buffer);
*line = get_line(backup[fd]);
backup[fd] = get_backup(backup[fd]);
if (buffsize == 0)
return (0);
return (1);
}