-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
108 lines (99 loc) · 2.81 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ihermell <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/11/08 14:35:35 by ihermell #+# #+# */
/* Updated: 2014/12/04 20:41:34 by ihermell ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include "get_next_line.h"
static int gnl_has_newline(t_buff *fd)
{
while (fd->buff[fd->read] != '\n' && fd->buff[fd->read] != '\0')
fd->read++;
return ((fd->buff[fd->read] == '\n') ? 1 : 0);
}
static char *gnl_buff_join(t_buff *fd, char *buff, int read_buff_len)
{
int i;
int k;
int j;
char *new;
if (read_buff_len == 0)
return (fd->buff);
i = 0;
k = fd->last_line + 1;
fd->read -= k;
new = (char*)malloc(sizeof(char) * (fd->len - k + read_buff_len + 1));
j = fd->len - fd->last_line - 1;
while (i < j)
new[i++] = fd->buff[k++];
k = 0;
while (k < read_buff_len)
new[i++] = buff[k++];
fd->len = fd->len - (fd->last_line + 1) + read_buff_len;
fd->last_line = -1;
new[i] = '\0';
return (new);
}
static int gnl_get_buffer_line(t_buff *fd, char **line)
{
int start;
int i;
char *temp;
start = (fd->last_line >= 0) ? fd->last_line + 1 : 0;
if (fd->buff[start] == '\0')
return (0);
i = 0;
*line = (char*)malloc(sizeof(char) * (fd->read - start));
while (start < fd->read)
(*line)[i++] = fd->buff[start++];
(*line)[i] = '\0';
if (fd->buff[fd->read] == '\n')
{
fd->last_line = fd->read;
fd->read++;
}
else
{
fd->len = 0;
fd->read = 0;
fd->last_line = -1;
FT_SWAP(fd->buff, ft_strnew(0), temp);
}
return (1);
}
void new_fd(t_buff *fd)
{
fd->last_line = -1;
fd->buff = ft_strnew(0);
fd->read = 0;
fd->len = 0;
}
int get_next_line(const int fd, char **line)
{
static t_buff buff_lst[256];
char *buff;
char *temp;
int r;
if (line == NULL || fd < 0 || fd > 255)
return (-1);
r = 1;
buff = (char*)malloc(sizeof(char) * (BUFF_SIZE + 1));
if (!buff_lst[fd].buff)
new_fd(buff_lst + fd);
while (!gnl_has_newline(&buff_lst[fd]) && r > 0)
{
r = read(fd, buff, BUFF_SIZE);
buff[r] = '\0';
FT_SWAP(buff_lst[fd].buff, gnl_buff_join(&buff_lst[fd], buff, r), temp);
}
free(buff);
if (r < 0)
return (-1);
return (gnl_get_buffer_line(&buff_lst[fd], line));
}