-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_line.c
52 lines (49 loc) · 1.12 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
#include "monty.h"
/**
* parse_line - it handles the tokenization of the string enter
*/
void parse_line(void)
{
int i = 0;
char *line_copy = NULL, *token = NULL;
line_copy = malloc(sizeof(char) * (strlen(file_ptr->line) + 1));
if (line_copy == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
strcpy(line_copy, file_ptr->line);
file_ptr->num_tokens = 0;
token = strtok(line_copy, " \n\t");
while (token)
{
file_ptr->num_tokens += 1;
token = strtok(NULL, " \n\t");
}
file_ptr->tokens = malloc(sizeof(char *) *
(file_ptr->num_tokens + 1));
if (file_ptr->tokens == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
free_file_ptr();
exit(EXIT_FAILURE);
}
strcpy(line_copy, file_ptr->line);
token = strtok(line_copy, " \n\t");
while (token)
{
file_ptr->tokens[i] = malloc(sizeof(char) *
(strlen(token) + 1));
if (file_ptr->tokens[i] == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
/* free_file_ptr(); */
exit(EXIT_FAILURE);
}
strcpy(file_ptr->tokens[i], token);
token = strtok(NULL, " \n\t");
i++;
}
file_ptr->tokens[i] = NULL;
free(line_copy);
}