-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathread_line.c
More file actions
74 lines (66 loc) · 1.02 KB
/
Copy pathread_line.c
File metadata and controls
74 lines (66 loc) · 1.02 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
73
74
#include "shell.h"
#include <unistd.h>
/**
* _getchar - man getchar
* Return: EOF
*/
int _getchar(void)
{
static char buffer[BUFFER_SIZE], *bufp = buffer;
static int n;
if (n == 0)
{
n = read(0, buffer, sizeof(buffer));
bufp = buffer;
}
if (--n >= 0)
{
return ((unsigned char) *bufp++);
}
return (EOF);
}
/**
* read_line - a pointer function that read the line from user.
*
* Return: line.
*/
char *read_line(void)
{
int position = 0, c, bufsize = BUFFER_SIZE;
char *buffer = malloc(sizeof(char) * bufsize);
if (!buffer)
{
perror("malloc");
exit(EXIT_FAILURE);
}
while (1)
{
c = _getchar();
if (c == EOF || c == '\n')
{
buffer[position] = '\0';
if (c == EOF && position == 0)
{
free(buffer);
return (NULL);
}
return (buffer);
}
else
{
buffer[position] = c;
}
position++;
if (position >= bufsize)
{
bufsize += BUFFER_SIZE;
buffer = realloc(buffer, bufsize);
if (!buffer)
{
perror("malloc");
exit(EXIT_FAILURE);
}
}
}
return (buffer);
}