-
Notifications
You must be signed in to change notification settings - Fork 1
/
mygetline.c
65 lines (56 loc) · 1.08 KB
/
mygetline.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
#include "shell.h"
ssize_t mygetline(char **buff, size_t *n, FILE *stream)
{
static size_t offset, len_input;
static int counter;
static ssize_t m;
static char *input;
size_t line_size, pos;
int fd;
line_size = 0;
if (offset == 0)
{
fd = fileno(stream);
input = malloc(sizeof(char) * 1024);
m = read(fd, input, 1024);
}
if (m > 0)
{
if (input[m - 1] == '\n')
input[m] = '\0';
else
{
input[m] = '\n';
input[m + 1] = '\0';
}
len_input = str_len(input);
if (counter > 0)
offset++;
pos = offset;
while (input[offset] != '\n')
{
line_size++;
offset++;
}
if (*n <= line_size)
*buff = malloc(sizeof(char) * (line_size + 2));
if (*buff == NULL)
{
printf("Error: memory allocation failed");
return (-1);
}
if (counter == 0)
mem_cpy(*buff, input, line_size + 1);
else
mem_cpy(*buff, (input + pos), line_size + 1);
mem_cpy((*buff + line_size + 1), "\0", 1);
}
if (offset + 1 == len_input || line_size == 0 || !(str_cmp(*buff, "exit\n")))
{
free(input);
offset = 0;
}
else
counter++;
return (line_size + 1);
}