Mohammad Fayaz Roll No.: Ap21110011426 Implementation of Lexical Analyzer using c-programming. Program Code



Download 16.33 Kb.
Date22.09.2023
Size16.33 Kb.
#62138
01 Lab

Compiler Design Lab Assignment-01
Name: Mohammad Fayaz
Roll No.: AP21110011426

Implementation of Lexical Analyzer using C-Programming.


Program Code:

#include


#include
#include
#include

int isKeyword(char b[]) {


char keywords[32][10] = {"auto", "break", "case", "char", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return", "short", "signed",
"sizeof", "static", "struct", "switch", "typedef", "union",
"unsigned", "void", "volatile", "while"};
int i, flag = 0;
for (i = 0; i < 32; ++i) {
if (strcmp(keywords[i], b) == 0) {
flag = 1;
break;
}
}
return flag;
}

int main() {


char ch, prev = '\0';
char b[15], oper[] = "+-*/%=<>";
FILE *fp;
int i, j = 0;
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("error while opening the file\n");
exit(0);
}
while ((ch = fgetc(fp)) != EOF) {
for (i = 0; i < 6; ++i) {
if (ch == oper[i])
printf("%c is operator\n", ch);
}

if (isdigit(ch)) {


b[j++] = ch;
b[j] = '\0';
printf("%s is constant\n", b);
j = 0;
} else if (isalpha(ch)) {
b[j++] = ch;
} else if ((ch == ',' || ch == ';' || ch == '(' || ch == ')' || ch == ']' || ch == '[' || ch == '{' || ch == '}' || ch == '\"' || ch == '\'' || ch==':' || ch=='.') && ch != prev) {
printf("%c is delimiter\n", ch);
prev = ch;
} else if ((ch == ' ' || ch == '\n') && (j != 0)) {
b[j] = '\0';
j = 0;

if (isKeyword(b) == 1)


printf("%s is keyword\n", b);
else
printf("%s is identifier\n", b);
}
}
fclose(fp);
return 0;
}

Input file content:
int main()
{
double x = 3 ;
int y = 5 ;
long sum = x + y ;
return 0 ;
}

Output:

int is keyword


( is delimiter
) is delimiter
main is identifier
{ is delimiter
double is keyword
x is identifier
= is operator
3 is constant
; is delimiter
int is keyword
y is identifier
= is operator
5 is constant
long is keyword
sum is identifier
= is operator
x is identifier
+ is operator
y is identifier
return is keyword
0 is constant
} is delimiter
Download 16.33 Kb.

Share with your friends:




The database is protected by copyright ©ininet.org 2024
send message

    Main page