-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
91 lines (82 loc) · 2.36 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* get_next_line.c :+: :+: */
/* +:+ */
/* By: jaberkro <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/01/19 21:12:24 by jaberkro #+# #+# */
/* Updated: 2022/01/24 15:43:51 by jaberkro ######## odam.nl */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int gnl_strlen(char *input);
int gnl_strchr_nl(char *input);
static void gnl_memmove(char *input, int start, int len)
{
int i;
i = 0;
while (i + start < len)
{
input[i] = input[start + i];
i++;
}
input[i] = '\0';
}
static char *gnl_strjoin(char *s1, char *s2, int s1len, int s2len)
{
int i;
char *out;
i = 0;
out = malloc(s1len + s2len + 1);
if (out == NULL)
return (NULL);
while (i < s1len + s2len)
{
if (i < s1len)
out[i] = s1[i];
else
out[i] = s2[i - s1len];
i++;
if (i > s1len && out[i - 1] == '\n')
{
gnl_memmove(s2, i - s1len, s2len);
break ;
}
}
out[i] = '\0';
free(s1);
return (out);
}
char *free_return(char *tofree)
{
free(tofree);
return (NULL);
}
char *get_next_line(int fd)
{
static char buf[BUFFER_SIZE + 1];
char *output;
int buflen;
output = gnl_strjoin(NULL, buf, 0, gnl_strlen(buf));
if (output == NULL || gnl_strchr_nl(output) != -1)
return (output);
buflen = read(fd, buf, BUFFER_SIZE);
if (buflen == -1 || (buflen == 0 && output[0] == '\0'))
return (free_return(output));
while (buflen != 0 && gnl_strchr_nl(output) == -1)
{
output = gnl_strjoin(output, buf, gnl_strlen(output), buflen);
if (output == NULL || gnl_strchr_nl(output) != -1)
return (output);
buflen = read(fd, buf, BUFFER_SIZE);
if (buflen == -1)
return (free_return(output));
}
if (output != NULL && gnl_strchr_nl(output) == -1)
buf[0] = '\0';
return (output);
}