Okay so I am writing a c code where I have to type a word, find it in a file, an
ID: 3604748 • Letter: O
Question
Okay so I am writing a c code where I have to type a word, find it in a file, and print the line and also count the amount of times the word appears. I do not know a way to count amount of times my "target" word appears while scanning "word", or each line. I need help writing something to count amount of times the word appears. This is what I have so far
while (fgets(word, MAX, inp) != NULL) {
if (strstr(word, target) != NULL) {
printf("Found %s on line %d: %s ", target, line, word);
}
line++;
}
}
printf("The string: "%s" was found a total of %d times in the file: %s ", target, count, file);
fclose(inp);
Explanation / Answer
Please find my code to count number of times a word occurs in file:
// count number of times 'key' appears in file 'in'
int countWord(char *in, char *key, int buf){
int count = 0;
FILE *f;
f = fopen(in,"r"); // opening file
char temp[buf]; // buffer to read line by line
while(fgets(temp,buf,f) != NULL){
char *p = temp;
while((p=(strstr(p,key)))!= NULL){ // breaking line uisng key
count++;
++p;
}
}
fclose(f);
return count;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.