-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_getline.c
More file actions
125 lines (104 loc) · 2.09 KB
/
Copy pathcustom_getline.c
File metadata and controls
125 lines (104 loc) · 2.09 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include "main.h"
/**
* malloc_usable_size - malloc
* @ptr: pointer
* Return: Pointer.
*/
size_t malloc_usable_size(const void *ptr)
{
size_t *size_ptr;
if (ptr == NULL)
return (0);
size_ptr = (size_t *)ptr - 1;
return (*size_ptr);
}
/**
* _getc - fucntion checks if it is end of line or not
* @stream: the stream
* Return: should return either 0 o 1
*/
int _getc(FILE *stream)
{
char ch;
ssize_t bytes_read = read(fileno(stream), &ch, 1);
return ((bytes_read == 1) ? ch : EOF);
}
/**
* _realloc - fucntion realocates memory
* @ptr: string is being relocated
* @size: new allocation
* Return: should return new realocated memory
*/
void *_realloc(void *ptr, size_t size)
{
void *new_ptr;
size_t original_size, copy_size;
if (ptr == NULL)
return (malloc(size));
if (size == 0)
{
free(ptr);
return (NULL);
}
new_ptr = malloc(size);
if (new_ptr == NULL)
return (NULL);
original_size = malloc_usable_size(ptr);
copy_size = (original_size < size) ? original_size : size;
_memcpy(new_ptr, ptr, copy_size);
free(ptr);
return (new_ptr);
}
/**
* _getline - takes inputt from user
* @lineptr: address of input
* @n: buffer
* @stream: STDIN
* Return: should return either -1 or 0
*/
ssize_t _getline(char **lineptr, size_t *n, FILE *stream)
{
int ch;
size_t len = 0;
char *new_lineptr;
if (lineptr == NULL || n == NULL || stream == NULL)
return (-1);
if (*lineptr == NULL)
*n = 0;
while ((ch = _getc(stream)) != EOF)
{
if (len + 1 >= *n)
{
*n += 1024 * 8;
new_lineptr = _realloc(*lineptr, *n);
if (new_lineptr == NULL)
return (-1);
*lineptr = new_lineptr;
}
(*lineptr)[len++] = ch;
if (ch == '\n')
break;
}
if (len == 0 || ch == EOF)
return (-1);
(*lineptr)[len] = '\0';
return (len);
}
/**
*_getenv - gets value of variable
*@var: variable
*Return: pointer to variable value
*/
char *_getenv(char *var)
{
size_t len = _strlen(var);
char **env = environ;
if (var == NULL)
return (NULL);
for (; *env != NULL; env++)
{
if (_strncmp(*env, var, len) == 0 && (*env)[len] == '=')
return (*env + len + 1);
}
return (NULL);
}