-
Notifications
You must be signed in to change notification settings - Fork 0
/
p1_v1.c
100 lines (89 loc) · 1.96 KB
/
p1_v1.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Version 1
// Reads character by character from file
// and prints immediately a token is discovered
#include <stdio.h>
#include <string.h>
int state = 0, bcount = 0;
FILE *fp;
int reset() { bcount = 0; state = 0; fseek(fp, -1, SEEK_CUR); }
int isDigi(char ch) {
if(ch >= '0' && ch <= '9') return 1;
return 0;
}
int isIden(char ch) {
if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_') return 1;
return 0;
}
int isOper(char ch) {
if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '=') return 1;
return 0;
}
int isSymb(char ch) {
if(ch == '{' || ch == '}' || ch == '(' || ch == ')' || ch == ';' || ch == ',') return 1;
return 0;
}
int isWhit(char ch) {
if(ch == ' ' || ch == '\t' || ch == '\n') return 1;
return 0;
}
int isKeyw(char *b) {
if(!strcmp(b, "main") || !strcmp(b, "void") || !strcmp(b, "int")) return 1;
return 0;
}
void main() {
char buffer[128], ch;
fp = fopen("input_1.txt", "r");
while((ch = fgetc(fp)) != EOF) {
buffer[bcount++] = ch;
switch(state) {
case 0:
if(isDigi(ch))
state = 1;
if(isIden(ch))
state = 2;
if(isOper(ch))
state = 3;
if(isSymb(ch))
state = 4;
if(isWhit(ch))
bcount = 0;
break;
case 1:
if(!isDigi(ch)) {
buffer[bcount - 1] = '\0';
printf("Number: \t%s\n", buffer);
reset();
}
break;
case 2:
if(!isIden(ch) && !isDigi(ch)) {
buffer[bcount - 1] = '\0';
if(isKeyw(buffer)) printf("Keyword: \t%s\n", buffer);
else printf("Identifier: \t%s\n", buffer);
reset();
}
break;
case 3:
if(ch == '/' && buffer[bcount - 2] == '/')
state = 5;
if(!isOper(ch)) {
buffer[bcount - 1] = '\0';
printf("Operator: \t%s\n", buffer);
reset();
}
break;
case 4:
buffer[bcount - 1] = '\0';
printf("Symbol: \t%s\n", buffer);
reset();
break;
case 5:
if(ch == '\n') {
bcount = 0;
state = 0;
break;
}
}
}
fclose(fp);
}