Howdy, Stranger!

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

Categories

find how many times word appear in file

penguinopenguino Posts: 2Member
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.

[code]#include
#include
#include

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

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

printf("%d",found);
return 0;
}
[/code]

Thank you.
Sign In or Register to comment.