-
Notifications
You must be signed in to change notification settings - Fork 1
/
_getline.c
101 lines (98 loc) · 1.59 KB
/
_getline.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
#include "shell.h"
/**
* _getline - gets a line from fd or std input
* @lineptr: buffer to fill line with
* @fd: file descriptor
* Return: num of characters
*/
int _getline(char **lineptr, int fd)
{
int size = 1025;
int old_size = 0;
int r = 1;
int sum = 0;
static char buffer[1025];
static int begin;
static int end;
int c = 0;
int d;
if (fd == -2)
{
begin = 0;
end = 0;
}
if (lineptr == NULL)
{
return (0);
}
if (*lineptr == NULL)
{
*lineptr = malloc(sizeof(char) * size + 1);
if (*lineptr == NULL)
return (-1);
}
while (1)
{
if (begin == end)
{
while (sum < 1024 && r != 0)
{
r = read(fd, buffer + sum, 1024 - sum);
begin = 0;
sum += r;
end = sum;
/*printf("r : %d\n", r);*/
for (d = 0; r != 0 && d < end; d++)
if (buffer[d] == '\n')
r = 0;
}
if (sum == 0)
{
buffer[0] = 0;
return (sum);
}
buffer[sum] = 0;
sum = 0;
}
for (; buffer[begin]; begin++)
{
if (begin == 1024)
{
/*free(buffer);*/
/*(*lineptr)[c] = EOF;*/
/*return (c);*/
break;
}
/*printf("beginning for\n");//debug check*/
if (buffer[begin] == '\n')
{
(*lineptr)[c] = '\n';
begin++;
c++;
(*lineptr)[c] = '\0';
return (c);
}
else
{
(*lineptr)[c] = buffer[begin];
}
c++;
}
if (c + begin >= 1024)
{
old_size = size;
size = size + 1024;
*lineptr = _realloc(*lineptr, old_size, size);
if (*lineptr == NULL)
{
return (-1);
}
}
else
{
(*lineptr)[old_size + begin] = 0;
return (c);
}
/*printf("j: %d, i:%d, r:%d\n", j, i ,r);*/
}
}