Code:typedef enum tType {VAR_TYPE,VAR_NAME,INT_VALUE,TERMINATOR} TokenType; typedef struct{ TokenType type; char *value; }TokenEntry; /*copying from source to destination*/ void iStrCpy(char *src,char *dest){ while(*src != '\0'){ *dest++ = *src++; } *dest = *src; } /*check whether the input given ranfges from small a to small z and capital A to capital Z 0 is return if it is true and 1 is return if it is false*/ int isVar(char *strVar){ while (*strVar != '\0'){ if((*strVar >= 'a' && *strVar <= 'z') || (*strVar >= 'A' && *strVar <= 'Z')){ strVar++; } else{ return 1; } } return 0; } int isNum(char *intVar){ while (*intVar != '\0'){ if(*intVar >= 0 && *intVar <= 9){ intVar++; } else{ return 1; } } return 0; } int getAllToken(char *line,char tokenList[20][30]){ char token[50]; char *ptr = line; int i = 0; /*while is not the end of line get the token and store it into tokenList*/ while(*ptr != '\0'){ ptr = getNextToken(ptr,token); iStrCpy(token,tokenList[i]); i++; } return i; } char *getNextToken(char *ptr,char *token){ while((*ptr != '\0') && (*ptr == ' ')){ ptr++; } while((*ptr != '\0') && (*ptr != ' ')){ *token++ = *ptr++; } *token = '\0'; return ptr; } /*passing in token by token*/ void checkReserveWord(char tokenListSize,char tokenList[20][30]){ int i; int j = 0; int k; int l = 0; TokenEntry eType[20]; char *reserveWord[] = {"int","isVar","isNum",";"}; TokenType tType[20] = {VAR_TYPE,VAR_NAME,INT_VALUE,TERMINATOR}; for(i = 0; i <= tokenListSize; i++){ j = 0; while(j != 4){ k = iStrCmp(tokenList[i],reserveWord[j]); if(k == 0){ /*storing into an array of struct*/ eType[l].type = tType[j]; eType[l].value = tokenList[i]; l++; j = 4; } /*return 0 is true*/ else if(!(isVar(tokenList[i]))){ eType[l].type = tType[j]; eType[l].value = tokenList[i]; l++; j = 4; } else if(!(isNum(tokenList[i]))){ eType[l].type = tType[j]; eType[l].value = tokenList[i]; l++; j = 4; } else{ j++; } } } } void interpret(char *line){ char tokenList[20][30]; int count; count = getAllToken(line,tokenList); checkReserveWord(count,tokenList); } int main(int argc,char *argv[]){ FILE *fp; char line[1000]; if(argc != 2){ printf("Invalid number of files\n"); exit(1); } fp = fopen(argv[1],"r"); if(fp == NULL){ printf("Invalid file"); } /*get line by line from the file*/ while(!feof(fp)){ fgets(line,1000,fp); interpret(line); } return 0; } sample FILE int x ;
This program i wrote is suppose to store the the words tokenize from the file into an array of struct.I am also trying my best to write my own library functions as u can see which is the first few functions.I am also not using string tokenizer to extract the wrods but doin it in my own function.As much as it can be, functions in string.h library is avoided from being used.
To my knowledge everything works well untill tokenizing.However there is some problem when i m trying to retrieve the information in the array of struct.Can someone please advice me on this?