I have to write a code for my uni programming course, and I'm still a beginner so I need some help figuring out why the value of 'word1' disappears while the program is still running. I have to write a program which opens a .c file and counts specific reserved words, which I have saved in a .txt file. The code is:
int countResWords(FILE *filep){
int count=0;
char word1[20],word2[20],*pos,*token,*pch,*pch2;
FILE *rp;
rp=fopen("reservedWords.txt","r+");
if(rp==NULL){
perror("File cannot be opened.");
return -1;
}
else{
while(!feof(rp)){
fscanf(rp,"%s",&word1);
count=0;
while(!feof(filep)){
fscanf(filep,"%s",&word2);
if((pch=strchr(word2,'('))!=NULL){
token=strtok(word2,"(");
while(token!=NULL){
if((pch2=strchr(token,')'))!=NULL) strtok(token,")");
if(strcmp(token,word1)==0) count++;
token=strtok(NULL,"(");
}
}else if(strcmp(word2,word1)==0) count++;
}
printf("The reserved word %s was used %d times in the given code.",word1,count);
rewind(filep);
}
}
fclose(rp);
}
int main(int argc, char *argv[]) {
char filename[100];
FILE *fp;
puts("Give a FILE NAME with its FULL PATH.");
scanf("%s",&filename);
fp=fopen(filename,"r+");
if(fp==NULL){
perror("File cannot be opened.");
return -1;
}
else countResWords(fp);
fclose(fp);
}
and the .c file i'm currently testing is:
#include <stdio.h>
#include <stdlib.h>
void selection(void);
void enterText(void);
void enterVoc(void);
void correctText(void);
void statistics(void);
void addWord(void);
void replaceWord(void);
void count(void);
void selection(void){
puts("selection");
}
void enterText(void){
puts("enterText");
}
void enterVoc(void){
puts("enterVoc");
}
void correctText(void){
puts("correctText");
}
void statistics(void){
puts("statistics");
}
void addWord(void){
puts("addWord");
}
void replaceWord(void){
puts("replaceWord");
}
void count(void){
puts("count");
}
int main(int argc, char *argv[]) {
selection();
enterText();
enterVoc();
correctText();
statistics();
addWord();
replaceWord();
count();
return 0;
}
somewhere along the line the variable word1 loses its value, and at the printing at the bottom of the countResWords function it doesn't print the word1 like it doesn't exist.