-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_function.c
50 lines (47 loc) · 1.06 KB
/
token_function.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
#include "shell.h"
/**
* command_tokens - Function splits user's command input into tokens
* @cmd_input: pointer to inputted command
* @file: size of file read
* Return: array of pointer to strings
*/
char **command_tokens(char *cmd_input, ssize_t file)
{
char *tok, *cmd_input_cpy, **cmd;
int tok_len, tok_cnt = 0, i = 0;
cmd_input_cpy = malloc(sizeof(char) * (file + 2));
if (cmd_input_cpy == NULL)
{
perror("Error: Memory Allocation Failed");
free(cmd_input_cpy);
return (NULL);
}
_strcpy(cmd_input_cpy, cmd_input);
tok = _strtok(cmd_input, " \n");
while (tok)
{
tok_cnt++;
tok = _strtok(NULL, " \n");
}
tok_cnt++;
cmd = malloc(sizeof(char *) * tok_cnt);
if (cmd == NULL)
{
perror("Error: Memory Allocation Failed");
free(cmd);
return (NULL);
}
tok = _strtok(cmd_input_cpy, " \n");
for (i = 0; tok != NULL; i++)
{
tok_len = _strlen(tok);
cmd[i] = malloc(sizeof(char) * tok_len + 1);
cmd[i][tok_len] = '\0';
_strcpy(cmd[i], tok);
tok = _strtok(NULL, " \n");
}
free(tok);
cmd[i] = NULL;
free(cmd_input_cpy);
return (cmd);
}