-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
118 lines (102 loc) · 1.89 KB
/
utils.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
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
#include "main.h"
/**
* gettoksnum - get number of tokens for malloc
* @line: single line read from stdin
* @size: size of line
* @delim: delimiters
* Return: Int, number of toks
*/
int gettoksnum(char *line, int size, char *delim)
{
int toksnum = 0;
char *cpstr, *tok;
if (size <= 0 || !line || !line[0])
return (0);
cpstr = _strdup(line);
if (!cpstr)
return (0);
tok = strtok(cpstr, delim);
while (tok != NULL)
{
if (tok[0] == '#')
break;
tok = strtok(NULL, delim);
toksnum++;
}
free(cpstr);
return (toksnum);
}
/**
* _strtok - tokenize user inputs
* @line: cmd red from stdin
* @size: size of @line
* @delim: token delimiter
* Return: array of ptrs to tokens
*/
char **_strtok(char *line, int size, char *delim)
{
int i, j, toksnum;
char *tok, **toks;
toksnum = gettoksnum(line, size, delim);
if (toksnum <= 0)
return (NULL);
toks = malloc(sizeof(char *) * (toksnum + 1));
if (!toks)
return (NULL);
tok = strtok(line, delim);
i = 0;
while (tok != NULL)
{
if (tok[0] == '#')
break;
toks[i] = _strdup(tok);
if (!toks[i])
{
for (j = 0; j < i; j++)
{
free(toks[i]);
}
free(toks);
return (NULL);
}
tok = strtok(NULL, delim);
i++;
}
toks[i] = NULL;
return (toks);
}
/**
* free_toks - free mem allocated to tokens
* @tokens: array of toks
*/
void free_toks(char **tokens)
{
int i = 0;
while (tokens && tokens[i])
free(tokens[i++]);
free(tokens);
}
/**
* _realloc - reallocate mem
* @old_size: old size of ptr
* @newsize: size of new mem block
* @ptr: pointer to old block
* Return: char pointer or NULL
*/
char *_realloc(char *ptr, int old_size, int newsize)
{
char *newptr;
if (newsize == 0 && ptr != NULL)
{
free(ptr);
return (NULL);
}
if (newsize == old_size)
return (ptr);
newptr = malloc(newsize);
if (ptr == NULL)
return (newptr);
newptr = _strcpy(newptr, ptr);
free(ptr);
return (newptr);
}