-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplit_str.c
executable file
·75 lines (69 loc) · 1.25 KB
/
split_str.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
69
70
71
72
73
74
75
#include "shell.h"
char *copy_str(char **strp, char *str, char **arg, char *tok);
/**
* split_str - split string
* @str: string
* @tok: character
*
* Return: pointer to array of string
*/
char **split_str(char *str, char *tok)
{
char **command = NULL, *arg, *strp;
int len, i;
if (str && tok)
{
if (!copy_str(&strp, str, &arg, tok))
return (NULL);
len = 1;
while (((arg = strtok(NULL, tok)) != NULL))
len++;
free(strp);
arg = strtok(str, tok);
if (arg)
{
command = malloc(sizeof(char *) * (len + 1));
if (!command)
exit(EXIT_FAILURE);
i = 0;
while (arg)
{
len = _strlen(arg);
command[i] = malloc(sizeof(char) * (len + 1));
if (!command[i])
{
_free(command);
exit(EXIT_FAILURE);
}
_strcpy(command[i], arg);
i++;
arg = strtok(NULL, tok);
}
command[i] = NULL;
}
}
return (command);
}
/**
* copy_str - copy string
* @strp: pointer
* @str: string
* @arg: pointer
* @tok: string
*
* Return: NULL or arg
*/
char *copy_str(char **strp, char *str, char **arg, char *tok)
{
*strp = malloc(sizeof(char) * (_strlen(str) + 1));
if (!(*strp))
return (NULL);
_strcpy(*strp, str);
*arg = strtok(*strp, tok);
if (!(*arg))
{
free(*strp);
return (NULL);
}
return (*arg);
}