forked from mwanyambu/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_getline.c
55 lines (51 loc) · 917 Bytes
/
_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
#include "main.h"
/**
* _getline - allocates memory to a line from stream
* @lineptr: pointer to buffer
* @n: buffer size
* @stream: stream
* Return: char count else -1
*/
ssize_t _getline(char **lineptr, size_t *n, FILE *stream)
{
size_t buffer_size = 0;
ssize_t bytes_read = 0;
int ch;
char *line = NULL, *line2;
if (lineptr != NULL && n != NULL && stream != NULL)
{
while ((ch = getc(stream)) != EOF)
{
if ((size_t)bytes_read + 1 >= buffer_size)
{
buffer_size = (buffer_size + 1) * 2;
line2 = realloc(line, buffer_size);
if (!line2)
{
free(line);
return (-1);
}
line = line2;
}
line[bytes_read++] = ch;
if (ch == '\n')
{
break;
}
}
if (bytes_read == 0)
{
free(line);
return (-1);
}
line[bytes_read] = '\0';
*lineptr = line;
*n = buffer_size;
return (bytes_read);
}
else
{
errno = EINVAL;
return (-1);
}
}