-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
109 lines (97 loc) · 2.47 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lpicoli- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/29 12:26:35 by lpicoli- #+# #+# */
/* Updated: 2023/06/25 21:20:27 by lpicoli- ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_new_line(char *stash)
{
char *tmp;
int i;
if (!*stash)
return (NULL);
i = 0;
while (stash[i] && stash[i] != '\n')
i++;
tmp = ft_calloc(i + 2, sizeof(char));
i = 0;
while (stash[i] && stash[i] != '\n')
{
tmp[i] = stash[i];
i++;
}
tmp[i] = stash[i];
return (tmp);
}
char *get_rest(char *stash)
{
char *tmp;
int i;
int index;
index = 0;
i = 0;
while (stash[i] && stash[i] != '\n')
i++;
if (!*stash) //(!stash) != (!*stash)
{
free(stash);
return (NULL);
}
tmp = ft_calloc(ft_strlen(stash) - i + 1, sizeof(char));
while (stash[i])
tmp[index++] = stash[++i];
tmp[index] = '\0';
free(stash);
return (tmp);
}
void *ft_free(char **stash, char **buffer)
{
free(*buffer);
free(*stash);
*stash = NULL;
return (NULL);
}
char *get_next_line(int fd)
{
int read_len;
char *buffer;
char *line;
static char *stash;
read_len = BUFFER_SIZE;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
buffer = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
while (!(ft_find_newline(buffer)) && read_len != 0)
{
read_len = read(fd, buffer, BUFFER_SIZE);
if (read_len == -1)
return (ft_free(&stash, &buffer));
buffer[read_len] = '\0';
stash = ft_join_stash(stash, buffer);
}
line = get_new_line(stash);
stash = get_rest(stash);
free(buffer);
return (line);
}
/* int main()
{
int fd;
char *ptr;
fd = open("text.txt", O_RDONLY);
ptr = get_next_line(fd);
printf("%s", ptr);
free(ptr);
ptr = get_next_line(fd);
printf("%s", ptr);
free(ptr);
ptr = get_next_line(fd);
printf("%s", ptr);
free(ptr);
} */