-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
103 lines (95 loc) · 2.25 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guferrei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/22 19:17:20 by guferrei #+# #+# */
/* Updated: 2021/07/04 23:07:59 by guferrei ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <unistd.h>
#include "get_next_line.h"
char *line_cpy(char *src)
{
int size;
int c;
char *dest;
size = 0;
c = 0;
while (*(src + size))
{
if (*(src + size) == '\n')
break ;
size++;
}
dest = malloc((size + 1) * sizeof(char));
if (!dest)
return (NULL);
while (c < size)
{
*(dest + c) = *(src + c);
c++;
}
*(dest + c) = '\0';
return (dest);
}
char *newline_cpy(char **stt)
{
char *new_stt;
char *aux;
aux = *stt;
while (*aux && *aux != '\n')
aux++;
if (*aux == '\n')
aux++;
new_stt = malloc((gnl_strlen(aux) + 1) * sizeof(char));
if (!new_stt)
return (NULL);
gnl_strcpy(aux, new_stt);
free(*stt);
return (new_stt);
}
int free_and_return(char **pt1, char **pt2, int i)
{
if (i == -1)
{
free (*pt1);
free (*pt2);
*pt2 = NULL;
return (-1);
}
else
{
free (*pt2);
*pt2 = NULL;
return (0);
}
}
int get_next_line(int fd, char **line)
{
static char *stt;
char *buffer;
int size;
buffer = safety_first(fd, line);
if (!buffer)
return (-1);
size = 1;
while (size > 0 && gnl_strchr(stt) > 0)
{
size = read(fd, buffer, BUFFER_SIZE);
if (size < 0)
return (free_and_return(&buffer, &stt, -1));
*(buffer + size) = '\0';
stt = gnl_strjoin(buffer, &stt);
}
free (buffer);
*line = line_cpy(stt);
stt = newline_cpy(&stt);
if (size == 0)
return (free_and_return(&buffer, &stt, 0));
else
return (1);
}