-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake-tokens.c
More file actions
71 lines (54 loc) · 1.64 KB
/
make-tokens.c
File metadata and controls
71 lines (54 loc) · 1.64 KB
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
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_INPUT_SIZE 1024
#define MAX_TOKEN_SIZE 64
#define MAX_NUM_TOKENS 64
char **tokenize(char *line)
{
char **tokens = (char **)malloc(MAX_NUM_TOKENS * sizeof(char *));
char *token = (char *)malloc(MAX_TOKEN_SIZE * sizeof(char));
int i, tokenIndex = 0, tokenNo = 0;
for(i =0; i < strlen(line); i++){
char readChar = line[i];
if (readChar == ' ' || readChar == '\n' || readChar == '\t') {
token[tokenIndex] = '\0';
if (tokenIndex != 0){
tokens[tokenNo] = (char*)malloc(MAX_TOKEN_SIZE*sizeof(char));
strcpy(tokens[tokenNo++], token);
tokenIndex = 0;
}
}
else {
token[tokenIndex++] = readChar;
}
}
free(token);
tokens[tokenNo] = NULL ;
return tokens;
}
void main(void)
{
char line[MAX_INPUT_SIZE];
char **tokens;
int i;
while (1) {
printf("Hello>");
bzero(line, MAX_INPUT_SIZE);
gets(line);
printf("Got command %s\n", line);
line[strlen(line)] = '\n'; //terminate with new line
tokens = tokenize(line);
//do whatever you want with the commands, here we just print them
for(i=0;tokens[i]!=NULL;i++){
printf("found token %s\n", tokens[i]);
}
// Freeing the allocated memory
for(i=0;tokens[i]!=NULL;i++){
free(tokens[i]);
}
free(tokens);
}
}