-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.c
51 lines (44 loc) · 776 Bytes
/
token.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
#include "shell.h"
/**
* tokenize - splits a string into an array
*
* @s: input string
* Return: an array
*/
char **tokenize(char *s)
{
char **argv;
char *token;
size_t bufsize, i;
bufsize = TOKEN_BUFSIZE;
argv = malloc(sizeof(char *) * (bufsize));
if (!argv)
{
free(argv);
return (NULL);
}
token = strtok(s, TOKEN_DELIM);
if (!token)
{
free(argv);
return (NULL);
}
argv[0] = token;
for (i = 1; token; i++)
{
if (i == bufsize)
{
bufsize += TOKEN_BUFSIZE;
argv = _realloc2(argv, sizeof(char *) * i, sizeof(char *) * bufsize);
if (argv == NULL)
{
free(argv);
write(STDERR_FILENO, ": allocation error\n", 18);
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, TOKEN_DELIM);
argv[i] = token;
}
return (argv);
}