Assignment 2
Assignment 2
-2
Question:-Design a lexical analyzer for given language and the lexical ananlyzer should ignore
redundant spaces,tabs and new lines.it should also ignore comments.although the syntax
specifictions states that identifiers can be arbitrarily long,you may restrict the length to some
resonable value.Simulate the same in C language. After lexical analysis seperate file for each type
of tokens will be created
Code:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
word[i] = '\0';
handleIdentifierOrKeyword(word);
ungetc(ch, sourceFile);
i = 0;
}
// Handle numbers
else if (isdigit(ch)) {
word[i++] = ch;
while (isdigit((ch = fgetc(sourceFile)))) {
word[i++] = ch;
}
word[i] = '\0';
handleNumber(word);
ungetc(ch, sourceFile);
i = 0;
}
// Handle operators and punctuation
else if (strchr("+-*/=<>!%&|^;,.(){}", ch)) {
handleOperatorOrPunctuation(ch);
}
}
}
int main() {
FILE *sourceFile = fopen("source_code.txt", "r");
if (sourceFile == NULL) {
printf("Error opening source code file.\n");
return 1;
}
return 0;
}
output:-
source_code.txt (Input File):
int main() {
int x = 10;
float y = 20.5;
if (x < y) {
x = x + 1;
}
return 0;
}
Generated Files:
1.keywords.txt:
int
float
if
return
2.identifiers.txt:
main
x
y
3.numbers.txt:
10
20
5
1
0
4. operators_and_punctuation.txt:
(
)
=
<
+
;
{
}
;