-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathparser.c
64 lines (55 loc) · 1.29 KB
/
parser.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
#include "shell.h"
/**
* tokenize - parsing user input into arguments
* by splits an array string into tokens using a delimiter.
* @str: the string to be tokenized.
* @delim: the delimiter used to split the string.
*
* Return: an array of pointers to the tokens,
* or NULL if an error occurs.
*/
char **tokenize(char *str, const char *delim)
{
char *token = NULL;
char **ret = NULL;
int i = 0;
token = strtok(str, delim);
while (token)
{
ret = realloc(ret, sizeof(char *) * (i + 1));
if (ret == NULL)
return (NULL);
ret[i] = malloc(_strlen(token) + 1);
if (!(ret[i]))
return (NULL);
_strcpy(ret[i], token);
token = strtok(NULL, delim);
i++;
}
/*increase the size of the array*/
ret = realloc(ret, (i + 1) * sizeof(char *));
if (!ret)
return (NULL);
ret[i] = NULL;
return (ret);
}
/**
* tokenize_input - splits a user input string into tokens with tokenize().
* @input: the user input string to be tokenized
*
* Return: an array of pointers to the tokens, or NULL if an error occurs
*/
char **tokenize_input(char *input)
{
char **tokens = NULL;
char *tmp = NULL;
tmp = _strdup(input);
if (tmp == NULL)
{
_puts("Memory allocation error\n");
exit(EXIT_FAILURE);
}
tokens = tokenize(tmp, " \t\r\n\a");
free(tmp);
return (tokens);
}