-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_line.c
41 lines (37 loc) · 917 Bytes
/
parse_line.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
#include "shell.h"
/**
* parse_line - Tokenize a string into an array of tokens.
*
* @line: The input string to be tokenized.
* @delimiter: The delimiter used to tokenize the string.
*
* This function takes a string as input and tokenizes into an array of
* string, separating tokens based on space and newline.
*
* Return: And array of tokens, with the last element is NULL.
*/
char **parse_line(char *line, char *delimiter)
{
int token_count = 0;
char *token;
char **tokens = malloc(strlen(line) * sizeof(char *));
if (!tokens)
return (NULL);
token = strtok(line, delimiter);
while (token)
{
tokens[token_count] = strdup(token);
if (!tokens[token_count])
{
free(token);
free(tokens[token_count]);
fprintf(stderr, "Error happens.");
exit(EXIT_FAILURE);
}
token_count++;
token = strtok(NULL, delimiter);
}
tokens[token_count] = NULL;
free(token);
return (tokens);
}