forked from Hassanyoung1/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_split.c
60 lines (54 loc) · 1.09 KB
/
token_split.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
#include "shell.h"
/**
* token_split - splits a string into tokens baesd on given delimiter
*
* @path: A string variable to be split
* @delim: delimeter to be used for spliting
* @argv: An array of array of strings
* @argv_size: size of argv
* Return: A pointer to splitted string
*/
int token_split(char *path, char *delim, char **argv, int argv_size)
{
char *token;
int count = 0, i = 0;
if (path == NULL || argv == NULL || argv_size <= 0)
{
free(path);
return (-1);
}
token = strtok(path, delim);
while (token != NULL && count < argv_size - 1)
{
argv[i] = malloc(_strlen(token) + 1);
if (argv[i] == NULL)
{
free_token_holder(argv);
free(path);
perror("memory allocation");
return (-1);
}
_strcpy(argv[i], token);
count++;
i++;
token = strtok(NULL, delim);
}
argv[i] = NULL;
free(path);
return (0);
}
/**
* free_token_holder - frees alocated memory in token_holder
*
* @token_holder: holder to be freed
* REturn: nothing
*/
void free_token_holder(char **token_holder)
{
int i = 0;
while (token_holder[i] != NULL)
{
free(token_holder[i]);
i++;
}
}