Quantcast
Viewing latest article 7
Browse Latest Browse All 2703

find how many times word appear on file

Hello, I'm trying to write a small program to check if a requested word appears in a row of a text document.

Not necessary to read the whole line if the requested word has been already found in that line.

Fox ex: We are looking for the word: "and" in the Document->
Jack and Jill
went up a hill
and saw a flower

In this case the result will be 2

The principles of the code are:
* Reading line by line and with every line, read word by word which will be stored in the word[] variable.
* string compare to check if the searched word is equal to the captured word from the line.

However it doesn't word and no idea how the debugger in C works as well, because it doesn't seem to be very informative.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *fp;
    fp = fopen("/home/yakir/test.txt","r");

    char *reqwrd = "and";
    char line[128];
    char word[20];
    int i=0;
    int w=0;
    int found=0;


    while((fgets(line,sizeof(line),fp)) !=NULL){
        i=0; w=0;
        printf("* %s",line); //get line from file to line
        //Jack and Jill

        //while not end of line and loaded word is not mach
        while((line[i] != '\n') || (strcmp(word,reqwrd) != 0)){
            memset(word,0,sizeof(word));
            w=0;
        //get a new word
            while(line[i] == ' ') i++;
            while(line[i] != ' ') word[w++] = line[i++];
            word[w]='\0';
        //word array has a new word
        }
        //either \n or word found

        //if the word was found
        if((strcmp(word,reqwrd) == 0))
        found++;
    }
fclose(fp);

printf("%d",found);
    return 0;
}


Thank you.

Viewing latest article 7
Browse Latest Browse All 2703

Trending Articles