Skip to content

Instantly share code, notes, and snippets.

@highoncarbs
Last active January 17, 2018 08:58
Show Gist options
  • Save highoncarbs/ffa58bd2fddfae7b42177d843de78360 to your computer and use it in GitHub Desktop.
Save highoncarbs/ffa58bd2fddfae7b42177d843de78360 to your computer and use it in GitHub Desktop.
Lexical Analyzer for C Language
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
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"};
int i , flag = 0;
for(int i = 0 ; i <32 ; i++){
if(strcmp(keywords[i] , buffer)==0){
flag = 1;
}
}
return flag;
}
int main(void) {
FILE *fp;
fp = fopen("test.c" , "r");
char ch , buffer[15] , ops[] = "*-/+%=" ;
int i , j = 0;
if(fp == NULL){
printf("Error opening the FILE.");
exit(0);
}
while((ch = fgetc(fp)) != EOF){
for(i = 0 ; i < 6 ; i++){
if(ch == ops[i]){
printf("%c is an operator \n" , ch);
}
}
if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch ==" " || ch == "\n") && (j != 0)){
buffer[j] = "\0";
j = 0;
if(isKeyword(buffer) == 1){
printf("%c is a Keyword \n" , buffer);
}
else{
printf("%c is an identifier \n" , buffer);
}
}
}
fclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment