-
Notifications
You must be signed in to change notification settings - Fork 1
/
tokenizer.c
68 lines (56 loc) · 1.27 KB
/
tokenizer.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
#include "shell.h"
/**
* tokenizer - Tokenizes a string into an array of strings.
* @line: The string to tokenize.
*
* Return: An array of strings (tokens), or NULL on failure.
*/
char **tokenizer(char *line)
{
char *token = NULL, *tmp = NULL;
char **command = NULL;
int cpt = 0, i = 0;
/* Check if the input string is NULL */
if (!line)
return (NULL);
/* Duplicate the input line to avoid modification */
tmp = _strdup(line);
/* Tokenize the duplicated line */
token = strtok(tmp, DELIM);
/* Handle the case when there are no tokens */
if (token == NULL)
{
free(line), tmp = NULL;
free(tmp), tmp = NULL;
return (NULL);
}
/* Count the number of tokens */
while (token)
{
cpt++;
token = strtok(NULL, DELIM);
}
/* Free the duplicated line */
free(tmp);
tmp = NULL;
/* Allocate memory for the array of strings (command) */
command = malloc(sizeof(char *) * (cpt + 1));
if (!command)
{
free(line);
return (NULL);
}
/* Tokenize the original line and store tokens in the command array */
token = strtok(line, DELIM);
while (token)
{
command[i] = _strdup(token);
token = strtok(NULL, DELIM);
i++;
}
/* Set the last element of the command array to NULL */
command[i] = NULL;
/* Free the original line */
free(line);
return (command);
}