#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Check if token is a keyword
int isKeyword(char *word) {
char *keywords[] = {"int", "float", "if", "else", "while", "for", "return"};
for (int i = 0; i < 7; i++) {
if (strcmp(word, keywords[i]) == 0)
return 1;
}
return 0;
}
// Check if token is a valid identifier
int isIdentifier(char *word) {
if (!(isalpha(word[0]) || word[0] == '_'))
return 0;
for (int i = 1; word[i] != '\0'; i++) {
if (!(isalnum(word[i]) || word[i] == '_'))
return 0;
}
return 1;
}
// Check if token is a number (literal)
int isNumber(char *word) {
for (int i = 0; word[i] != '\0'; i++) {
if (!isdigit(word[i]))
return 0;
}
return 1;
}
// Check if character is an operator
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=');
}
// Check if character is punctuation
int isPunctuation(char ch) {
return (ch == ',' || ch == ';' || ch == '(' || ch == ')' || ch == '{' || ch == '}');
}
int main() {
FILE *fp;
char filename[100], ch, word[100];
int i = 0;
printf("Enter file name: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: File not found.\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
if (isalnum(ch) || ch == '_') {
word[i++] = ch;
} else {
word[i] = '\0';
i = 0;
if (strlen(word) > 0) {
if (isKeyword(word))
printf("Keyword: %s\n", word);
else if (isNumber(word))
printf("Literal: %s\n", word);
else if (isIdentifier(word))
printf("Identifier: %s\n", word);
else
printf("Unknown token: %s\n", word);
}
if (isOperator(ch))
printf("Operator: %c\n", ch);
else if (isPunctuation(ch))
printf("Punctuation: %c\n", ch);
}
}
fclose(fp);
return 0;
}
Comments
Post a Comment