#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
// Function to check if a string is a keyword
int isKeyword(char buffer[])
{
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"
};
for(int i = 0; i < 32; ++i)
{
if(strcmp(keywords[i], buffer) == 0)
{
return 1; // Keyword found
}
}
return 0; // Not a keyword
}
// Function to check if a character is an operator
int isOperator(char ch)
{
char op[] = {'+', '-', '*', '/', '%', '='};
for(int i = 0; i < 6; i++)
{
if(ch == op[i])
{
return 1; // Operator found
}
}
return 0; // Not an operator
}
// Function to check if a character is a symbol
int isSymbol(char ch)
{
char sy[] = {',', ';', '(', ')', '{', '}'};
for(int i = 0; i < 6; i++)
{
if(ch == sy[i])
{
return 1; // Symbol found
}
}
return 0; // Not a symbol
}
int main()
{
char ch, buffer[15],token=0;
FILE *fp;
int j = 0;
// Open the file in read mode
fp = fopen("NUB.txt", "r");
if(fp == NULL)
{
printf("Error while opening the file\n");
exit(0);
}
printf("Lexical Analysis:\n\n");
while((ch = fgetc(fp)) != EOF)
{
// Check for alphanumeric characters
if(isalnum(ch))
{
buffer[j++] = ch; // Add to buffer
}
else
{
if(j != 0) // Process the buffer if it contains something
{
token++;
buffer[j] = '\0'; // Null-terminate the string
j = 0;
if(isKeyword(buffer))
printf("%s is a keyword\n", buffer);
else
printf("%s is an identifier\n", buffer);
}
// Check for operators
if(isOperator(ch))
{
token++;
printf("%c is an operator\n", ch);
}
// Check for symbols
else if(isSymbol(ch))
{
token++;
printf("%c is a symbol\n", ch);
}
}
}
printf("Total Token: %d \n\n",token);
fclose(fp); // Close the file
return 0;
}