-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
135 lines (124 loc) · 2.51 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
** get_next_line.c for get_next_line in /home/nicolaspolomack/cpe/CPE_2016_getnextline
**
** Made by Nicolas Polomack
** Login <[email protected]>
**
** Started on Mon Jan 2 12:59:49 2017 Nicolas Polomack
** Last update Tue May 16 10:20:55 2017 Arthur Knoepflin
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include "get_next_line.h"
char *line_cases(int fd, int *fd_s, char **final)
{
int i;
i = get_line_str(fd, final, READ_SIZE);
if (i > 0)
return (get_final_line(final));
else if (**final != 0)
{
*fd_s = -1;
return (*final);
}
else
{
free(*final);
*final = NULL;
return (NULL);
}
}
char *my_realloc(char *buffer, char *overflow)
{
int i;
int j;
char *temp;
i = -1;
j = -1;
while (overflow[++i]);
while (buffer[++j]);
if ((temp = malloc(i + j + 1)) == NULL)
return (NULL);
i = -1;
j = 0;
while (overflow[++i] != 0)
temp[i] = overflow[i];
while (buffer[j] != 0)
temp[i++] = buffer[j++];
temp[i] = 0;
free(overflow);
return (temp);
}
int get_line_str(const int fd, char **final, int size)
{
char buffer[size + 1];
int chars;
chars = -1;
while ((*final)[++chars] != 0)
if ((*final)[chars] == 10)
return (2);
chars = 1;
while ((chars = read(fd, buffer, READ_SIZE)) > 0)
{
buffer[chars] = 0;
if ((*final = my_realloc(buffer, *final)) == NULL)
return (-1);
chars = 0;
while ((*final)[chars] != 0)
{
if ((*final)[chars] == 10)
return (1);
chars += 1;
}
chars = 1;
}
return (0);
}
char *get_final_line(char **overflow)
{
char *final;
int i;
int j;
i = -1;
j = 0;
while ((*overflow)[++i] != 10);
if ((final = malloc(i + 1)) == NULL)
return (NULL);
i = -1;
while ((*overflow)[++i] != 10 && (*overflow)[i] != 0)
final[i] = (*overflow)[i];
final[i] = 0;
if ((*overflow)[i] == 0)
return (final);
while ((*overflow)[++i] != 0)
{
(*overflow)[j++] = (*overflow)[i];
(*overflow)[i] = 0;
}
while ((*overflow)[j] != 0)
(*overflow)[j++] = 0;
return (final);
}
char *get_next_line(const int fd)
{
static char *final = NULL;
static int fd_s = -1;
if (fd == -1)
{
free(final);
final = NULL;
fd_s = -1;
return (NULL);
}
if (READ_SIZE <= 0)
return (NULL);
if (final == NULL || (fd_s != fd && fd_s == -1))
{
fd_s = fd;
if ((final = malloc(1)) == NULL)
return (NULL);
*final = 0;
}
return (line_cases(fd, &fd_s, &final));
}