I am trying to create a lexical analyzer in C. The program reads another program
ID: 3547644 • Letter: I
Question
I am trying to create a lexical analyzer in C. The program reads another program as input to convert it into tokens, and the source code is here-
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
FILE *fp;
char read[50];
char seprators [] = " ";
char *p;
fp=fopen("C:\Sum.c", "r");
clrscr();
while ( fgets(read, sizeof(read)-1, fp) !=NULL ) {
//Get the first token
p=strtok(read, seprators);
//Get and print other tokens
while (p!=NULL) {
printf("%s ", p);
p=strtok(NULL, seprators);
}
}
return 0;
}
And the contents of Sum.c are-
#include <stdio.h>
int main() {
int x;
int y;
int sum;
printf("Enter two numbers ");
scanf("%d%d", &x, &y);
sum=x+y;
printf("The sum of these numbers is %d", sum);
return 0;
}
I am not getting the correct output and only see a blank screen in place of output.
Can anybody please tell me where am I going wrong?? Thank you so much in advance..
Explanation / Answer
Make sure you're file opens successfully. You never check it, often the current working directory at runtime isn't what you think, especially if you're running from an IDE or other such tool. Verify fopen() succeeded and if it didn't, perror("Failed to open file."); and exit. At least you'll know that was the issue.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.