-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
114 lines (105 loc) · 1.72 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
110
111
112
113
114
#include "get_next_line.h"
char *ft_read(int fd, char *stash)
{
char *buff;
int nbr_of_bytes;
buff = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buff)
return (NULL);
nbr_of_bytes = 1;
while (!ft_strchr(stash, '\n') && nbr_of_bytes != 0)
{
nbr_of_bytes = read(fd, buff, BUFFER_SIZE);
if (nbr_of_bytes == -1)
{
free(buff);
return (NULL);
}
buff[nbr_of_bytes] = '\0';
stash = ft_strjoin(stash, buff);
}
free(buff);
return (stash);
}
char *ft_line(char *stash)
{
int size;
int i;
char *str;
size = 0;
if (!stash[size])
return (NULL);
while (stash[size] && stash[size] != '\n')
size++;
str = (char *)malloc(sizeof(char) * (size + 2));
if (!str)
return (NULL);
i = 0;
while (stash[i] && stash[i] != '\n')
{
str[i] = stash[i];
i++;
}
if (stash[i] == '\n')
{
str[i] = stash[i];
i++;
}
str[i] = '\0';
return (str);
}
char *ft_rab(char *stash)
{
int i;
int size;
char *rab;
size = 0;
while (stash[size] && stash[size] != '\n')
size++;
if (!stash[size])
{
free(stash);
return (NULL);
}
rab = (char *)malloc(sizeof(char) * (ft_strlen(stash) - size + 1));
if (!rab)
return (NULL);
size++;
i = 0;
while (stash[size])
rab[i++] = stash[size++];
rab[i] = '\0';
free(stash);
return (rab);
}
char *get_next_line(int fd)
{
char *line;
static char *stash;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
stash = ft_read(fd, stash);
if (!stash)
return (NULL);
line = ft_line(stash);
stash = ft_rab(stash);
return (line);
}
/*
int main()
{
int fd;
char *line;
fd = open("texte1.txt", O_RDONLY);
line = get_next_line(fd);
int i = 1;
while (line)
{
printf("line %d: %s", i, line);
free(line);
line = get_next_line(fd);
i++;
}
close(fd);
return (0);
}*/