-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_getline.c
More file actions
53 lines (48 loc) · 1.01 KB
/
Copy path_getline.c
File metadata and controls
53 lines (48 loc) · 1.01 KB
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 - Custom getline function for reading input from a file descriptor.
*
* @lineptr: Pointer to the buffer storing the input line.
*
* @n: Pointer to the size of the buffer.
*
* @fd: File descriptor to read from.
*
* Return: Number of bytes read, or -1 on failure.
*/
ssize_t _getline(char **lineptr, size_t *n, int fd)
{
ssize_t bytes_read = 0;
size_t position = 0, new_size;
char str;
char *buffer;
if (lineptr == NULL || n == NULL)
return (-1);
if (*lineptr == NULL || *n == 0)
{
*lineptr = (char *)malloc(BUFFER_SIZE);
if (*lineptr == NULL)
return (-1);
*n = BUFFER_SIZE;
}
while (read(fd, &str, 1) > 0)
{
if (position >= *n - 1)
{
new_size = *n * 2;
buffer = (char *)realloc(*lineptr, new_size);
if (buffer == NULL)
return (-1);
*lineptr = buffer;
*n = new_size;
}
(*lineptr)[position++] = str;
bytes_read++;
if (str == '\n')
break;
}
if (bytes_read == 0)
return (-1);
(*lineptr)[position] = '\0';
return (bytes_read);
}