-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5-getline.c
More file actions
72 lines (65 loc) · 1.3 KB
/
Copy path5-getline.c
File metadata and controls
72 lines (65 loc) · 1.3 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "main.h"
ssize_t gb_getline(char **line_ptr, size_t *len_siz, FILE *stream);
/**
* gb_getline - This is our getline function getline function
* @line_ptr: line buffer
* @len_siz: length of buffer
* @stream: stream to read from
* Return: number of characters read or -1 if fail
*/
ssize_t gb_getline(char **line_ptr, size_t *len_siz, FILE *stream)
{
ssize_t read_char, p_len = 0;
char *the_getline;
char *line = *line_ptr, *new_line;
size_t size = *len_siz;
if (line == NULL || size == 0)
{
size = 1024;
line = malloc(size);
if (line == NULL)
return (-1);
}
while (1)
{
the_getline = fgets(line + p_len, (int)size, stream);
if (the_getline == NULL)
{
if (p_len == 0)
{
free(line);
*line_ptr = NULL;
*len_siz = 0;
return (-1);
}
else
{
*line_ptr = line;
*len_siz = size;
return (p_len);
}
}
read_char = gb_strlen(line + p_len);
if (read_char > 0 && line[read_char - 1] == '\n')
{
line[p_len + read_char - 1] = '\0';
*line_ptr = line;
*len_siz = size;
return (p_len + read_char);
}
p_len += read_char;
if (size - p_len <= 1)
{
size *= 2;
new_line = realloc(line, size);
if (new_line == NULL)
{
free(line);
*line_ptr = NULL;
*len_siz = 0;
return (-1);
}
line = new_line;
}
}
}