-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetline.c
77 lines (66 loc) · 1.26 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
#include "unixshell.h"
/**
* _getline - a function to read an entire line of text from stdin
* @linebuff: a pointer to char * that stores the text
* @n: the size of linebuff
*
* Return: Characters read
**/
ssize_t _getline(char **linebuff, size_t *n)
{
static int c;
ssize_t byte_read;
size_t i = 0;
memalloc(linebuff, n);
while ((byte_read = read(STDIN_FILENO, &c, 1)) > 0)
{
(*linebuff)[i] = c;
if (c == '\n')
{
(*linebuff)[i] = '\0';
return (i);
}
i++;
if (i >= *n)
{
*n += BUFFER_SIZE; /* Increase the buffer size */
*linebuff = (char *)_realloc(*linebuff, *n, (*n * 2));
if (*linebuff == NULL)
{
perror("realloc");
return (-1);
}
}
}
if (byte_read == -1)
{
perror("read");
free(*linebuff);
return (-1);
}
(*linebuff)[i] = '\0';
if (i == 0 && byte_read == 0)
return (-1); /* No characters read, reached EOF */
return (i);
}
/**
* memalloc- a function to allocate memory
* @linebuff: a pointer to char *
* @n: the unsigned int size
*
* Return: On success, 1, otherwise -1
**/
int memalloc(char **linebuff, size_t *n)
{
if (*linebuff == NULL || *n == 0)
{
*n = BUFFER_SIZE;
*linebuff = (char *)malloc(*n);
if (*linebuff == NULL)
{
perror("malloc");
return (-1);
}
}
return (1);
}