-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_getline.c
More file actions
53 lines (51 loc) · 979 Bytes
/
_getline.c
File metadata and controls
53 lines (51 loc) · 979 Bytes
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
#include "shell.h"
/**
* _getline - get line of text from file stream
* @lineptr: pointer to a pointer to a buffer
* @n: pointer to a size_t variable (bufsize)
* @stream: File stream to read text.
*
* Return: The number of bytes read
*/
ssize_t _getline(char **lineptr, size_t *n, FILE *stream)
{
char *buffer;
size_t bufsize, i;
ssize_t bytes_read;
int fd;
char c;
bufsize = 20, i = 0;
buffer = malloc(sizeof(char) * bufsize);
if (buffer == NULL)
{
perror("Memory Allocation");
return (-1);
}
fd = fileno(stream);
if (fd == -1)
{
perror("Error getting file descriptor");
free(buffer);
return (-1);
}
bytes_read = 0;
while (read(fd, &c, 1) == 1 && c != '\n')
{
buffer[bytes_read] = c;
bytes_read++;
i++;
if (i >= bufsize)
{
bufsize *= 2;
buffer = realloc(buffer, bufsize);
if (buffer == NULL)
{
perror("Memory Management error");
return (-1);
}
}
}
*n = bufsize;
*lineptr = buffer;
return (bytes_read);
}