-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenize_cmd.c
More file actions
52 lines (44 loc) · 1.15 KB
/
tokenize_cmd.c
File metadata and controls
52 lines (44 loc) · 1.15 KB
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
#include "main.h"
/**
* tokenize_cmd - splits input strings into tokens
* Returns: an array of tokens
*/
tokenized_data tokenize_cmd(char *input_string, const char *delimiter) {
int index, array_size, i;
tokenized_data data;
char *token;
index = 0;
array_size = 8;
data.tokens_count = 0;
data.tokens_array = malloc(sizeof(char *) * array_size);
if (data.tokens_array == NULL) {
perror("Memory allocation error");
return (data);
}
token = strtok(input_string, delimiter);
while (token != NULL) {
data.tokens_array[index] = strdup(token);
if (data.tokens_array[index] == NULL) {
perror("Memory allocation error");
for (i = 0; i < index; i++) {
free(data.tokens_array[i]);
}
free(data.tokens_array);
return (data);
}
index++;
data.tokens_count++;
if (index >= array_size) {
array_size *= 2;
data.tokens_array = reallocate_mem(data.tokens_array, (sizeof(char *) *(array_size - 1)),
(sizeof(char *) * array_size));
if (data.tokens_array == NULL) {
perror("Memory reallocation error");
return (data);
}
}
token = strtok(NULL, delimiter);
}
data.tokens_array[index] = NULL;
return (data);
}