-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.c
More file actions
72 lines (59 loc) · 1.11 KB
/
stream.c
File metadata and controls
72 lines (59 loc) · 1.11 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
#include "shell.h"
/**
* get_input - A function that read inputs from non-interactive mode.
*
* Return: String read
*/
char *get_input(void)
{
int buf_size = 1024, index = 0;
char *input = malloc(sizeof(char) * buf_size);
ssize_t bytesRead;
char c;
char *more_input = NULL;
if (!input)
{
perror("Memory allocation error");
exit(EXIT_FAILURE);
}
while ((bytesRead = read(STDIN_FILENO, &c, 1)) > 0)
{
if (c == '\n' || c == EOF)
break;
input[index++] = c;
if (index >= (buf_size - 1))
{
buf_size += 1024;
more_input = realloc(input, buf_size);
if (!more_input)
{
perror("Memory reallocation error");
free(input);
exit(EXIT_FAILURE);
}
input = more_input;
}
}
terminate(bytesRead, input);
input[index] = '\0'; /* I added a NULL Terminator */
return (input);
}
/**
* terminate - To check for EOF condition empty input condtions
* @n: number of bytes read
* @k: buffer being read
*/
void terminate(ssize_t n, char *k)
{
if (n == -1)
{
perror("Error reading from stdin");
free(k);
exit(EXIT_FAILURE);
}
if (n == 0)
{
free(k);
exit(EXIT_FAILURE);
}
}