Home > Mobile >  Getting words from the files and comparing them with the text in another file
Getting words from the files and comparing them with the text in another file

Time:10-04

I wanted to find the number of occurences of some specific words which are in the file2 as;
(word1)

(word2)

(word3)

For the first word, everything works fine as it finds the no. of occurences. But for the other two words the occurences equal to 0. Even though I tried to debug the program, I could not figure out why the other two words are skipped by the program. Because I am a beginner, maybe I did a mistake in the conditions of the two while loops, while I try to access each word. Could anyone help me to understand where am I doing wrong?

I appreciate your help

void count_words(FILE *file1, FILE *file2){
    char words[20], check_words[20];
    int occurrences = 0;

    while (fscanf(file2, "%s", words) != EOF){
        while (fscanf(file1, "%s", check_words) != EOF){
            for (int i=0; i<strlen(check_words); i  ){
                check_words[i] = tolower(check_words[i]);
            }
            if (strcmp(check_words, words) == 0){
                occurrences  ;
            }
        }
        printf("'%s' -> %d occurrence(s)\n", words, occurrences);
        occurrences = 0;
    }
}

CodePudding user response:

When you read from a file, the file pointer (like a cursor) moves.

The first time you read a word from file1, your loop will read all the words from file2. Now the file pointer is at the end of file2.

So the second time you read a word from file1, when you try to read a word from file2 you will fail, because file2 file pointer is at the end of the file. There are no more words - you used them all first time.

You need to either rewind file2 using the fseek(file2, 0, SEEK_SET) function to put the file pointer back to the start, or you need to solve the problem in a different way.

For example it is common to read the whole of both files into a data structure in memory and then match them from that data structure.

  • Related