-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenize.c
62 lines (52 loc) · 1 KB
/
tokenize.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
#include "main.h"
/**
* tokenize - Tokenize a string into separate args dynamically
* @input: The string to tokenize.
*
* Return: A pointer to an array of tokenized args or NULL on failure.
*/
char **tokenize(char *input)
{
int count = 0, size = 10;
char **args = malloc(sizeof(char *) * size), **tmp;
char *token;
if (args == NULL)
return (NULL);
args[0] = NULL;
token = _strtok(input, " \t");
while (token != NULL && *token != '#')
{
if (count + 1 >= size)
{
size += 10;
tmp = realloc(args, size);
if (!tmp)
{
free_tokenargs(args);
return (NULL);
}
args = tmp;
}
args[count] = _strdup(token);
if (args[count] == NULL)
{
free_tokenargs(args);
return (NULL);
}
args[++count] = NULL;
token = _strtok(NULL, " \t\n");
}
return (args);
}
/**
* free_tokenargs - Free memory allocated for tokenized args
* @args: The array of tokenized args
*/
void free_tokenargs(char **args)
{
int i = 0;
while (args[i])
free(args[i++]);
if (args)
free(args);
}