-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
78 lines (73 loc) · 2.61 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: iyahoui- <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/27 13:10:14 by iyahoui- #+# #+# */
/* Updated: 2021/10/05 11:25:35 by iyahoui- ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#ifndef BUFFER_SIZE
# define BUFFER_SIZE 1024
#endif
/* Reads to the static char *remain until a nl is found, or until
* the EOF has been reached. If read() reaches EOF (returns nbyte < BUFF_SIZE)
* or attempts an invalid read () (returns -1) and remain[fd] doesn't
* end with \n, get_line_len() returns 0.
*/
static long get_line_len(char **remain, int fd)
{
long read_status;
char *read_buf;
while (!(*remain) || !strlen_c(*remain, '\n'))
{
read_buf = malloc(BUFFER_SIZE + 1);
read_status = read(fd, read_buf, BUFFER_SIZE);
if (read_status <= 0)
{
free (read_buf);
return (read_status);
}
read_buf[read_status] = 0;
*remain = ft_strjoin_free(*remain, read_buf);
free(read_buf);
}
return (strlen_c(*remain, '\n'));
}
/* get_next_line is used to return the string content of a single input
* stream (fd) line by line. Every function call returns a line including
* the \n character.
* It uses static char *remain to store the excess buffer from the read()
* function (i.e. everything after \n). The second if checks if remain[fd] is
* empty. The last if is merely to ensure that free() happens as soon as the
* last line is hit. (could be removed to save 7 lines of code)
*/
char *get_next_line(int fd)
{
char *current_line;
long line_len;
static char *remain = NULL;
line_len = get_line_len(&remain, fd);
if (line_len <= 0)
line_len = strlen_c(remain, 0);
if (!line_len)
{
free (remain);
remain = (NULL);
return (NULL);
}
current_line = malloc(line_len + 1);
ft_strncpy(current_line, remain, line_len);
if (!strlen_c(remain, '\n'))
{
free (remain);
remain = (NULL);
}
else
ft_strncpy(remain, &remain[line_len], \
strlen_c(remain, 0) - line_len + 1);
return (current_line);
}