find how many times word appear in 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.


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] != '
') || (strcmp(word,reqwrd) != 0)){
//get a new word
while(line[i] == ' ') i++;
while(line[i] != ' ') word[w++] = line[i++];
//word array has a new word
or word found

//if the word was found
if((strcmp(word,reqwrd) == 0))

return 0;

Thank you.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!