-
Notifications
You must be signed in to change notification settings - Fork 0
/
getline_tools.c
92 lines (84 loc) · 2.29 KB
/
getline_tools.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "main.h"
/**
* refill_buffer - Refill the buffer by reading from the stream.
* @n_read: Pointer to the number of bytes read in the buffer.
* @buff: Buffer to store the read data.
* @stream: The stream to read from.
* Return: The number of bytes read, or -1 on failure.
*/
ssize_t refill_buffer(ssize_t *n_read, char *buff, FILE *stream)
{
*n_read = read(fileno(stream), buff, BUFFER_SIZE);
return (*n_read);
}
/**
* find_line_length - Find the length of the line in the buffer.
* @buff: Buffer containing the data.
* @n_read: Number of bytes read in the buffer.
* @pos: Current position in the buffer.
* Return: The length of the line, or 0 if no newline found.
*/
ssize_t find_line_length(char *buff, ssize_t n_read, ssize_t pos)
{
ssize_t line_len = 0;
ssize_t i;
for (i = pos; i < n_read; i++)
{
if (buff[i] == '\n')
{
line_len = i - pos + 1;
break;
}
}
return (line_len);
}
/**
* should_resize_buffer - Check if the buffer needs to be resized.
* @lineptr: Pointer to the buffer storing the read line.
* @n: Size of the buffer.
* @line_len: Length of the line to be stored.
* Return: 1 if the buffer needs to be resized, 0 otherwise.
*/
int should_resize_buffer(char **lineptr, ssize_t n, ssize_t line_len)
{
return (!*lineptr || n < line_len + 1);
}
/**
* resize_buffer - Resize the buffer to accommodate the line.
* @lineptr: Pointer to the buffer storing the read line.
* @n: Pointer to the size of the buffer.
* @line_len: Length of the line to be stored.
* Return: 0 on success, -1 on failure.
*/
ssize_t resize_buffer(char **lineptr, ssize_t *n, ssize_t line_len)
{
ssize_t new_size = *n + line_len + 1;
char *new_buff = malloc(new_size * sizeof(char));
if (!new_buff)
return (-1);
if (*lineptr)
{
memcpy(new_buff, *lineptr, *n);
free(*lineptr);
}
*lineptr = new_buff;
*n = new_size;
return (0);
}
/**
* copy_line_to_buffer - Copy the line from the buffer to the lineptr.
* @lineptr: Pointer to the buffer storing the read line.
* @buff: Buffer containing the data.
* @pos: Current position in the buffer.
* @line_len: Length of the line to be copied.
*/
void copy_line_to_buffer(char **lineptr, char *buff, ssize_t pos,
ssize_t line_len)
{
ssize_t i;
for (i = 0; i < line_len; i++)
{
(*lineptr)[i] = buff[pos + i];
}
(*lineptr)[line_len] = '\0';
}