realsdx

LEXRER

Feb 11th, 2020
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. #include<string.h>
  5.  
  6. int main(int argc, char const *argv[])
  7. {
  8.     char ch,buffer[100],operators[]="+.*/%=";
  9.     FILE *fp;
  10.     int i,j=0;
  11.  
  12.     // open the source file given in first argument
  13.     if(argc != 2)
  14.         printf("Source file is not provided.\n");
  15.  
  16.     fp=fopen(argv[1],"r");
  17.  
  18.     //if can't open file throw error
  19.     if(fp==NULL)
  20.     {
  21.         printf("Error while opening the file\n");
  22.         exit(2);   
  23.     }
  24.  
  25.     int fl=1, cnt=1;
  26.     //parse the file, one by one character
  27.     while((ch=fgetc(fp))!=EOF){
  28.  
  29.         //check if the char is a operator
  30.         for(i=0;i<6;i++)
  31.         {
  32.             if(ch==operators[i])
  33.             {
  34.                 printf("%c is operator\n",ch);
  35.                 if(!fl)buffer[j++]=',';            
  36.                 fl=1;
  37.             }
  38.         }
  39.         // cehck is the char is alphanumeric
  40.         if(isalnum(ch))
  41.         {
  42.             buffer[j++]=ch;
  43.             fl=0;
  44.         }
  45.         else if((ch=='\n')&& j!=0)
  46.         {
  47.             buffer[j]='\0';
  48.             j=0;
  49.             printf("%s is identifier\n",buffer);
  50.             fl=1;
  51.             printf("Above tokens are from line %d \n",cnt);
  52.  
  53.             // if the current char is a newline increase the newline counter
  54.             if( ch == '\n')
  55.                 cnt++;
  56.         }
  57.     }
  58.  
  59.     fclose(fp);
  60.  
  61.     return 0;
  62. }
Add Comment
Please, Sign In to add comment