Hey everyone!
I'm working on a program that reads in a .txt file and searches through the text for a keyword. If it gets a hit on the keyword, the line number where the keyword is located and the line that contains the keyword is printed out. What I have now doesn't catch every occurance of the keyword "a". Any ideas why?
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char line[1024];
char copy[1024];
char * pch;
int line_count = 0;
char test[2] = "a";
FILE* file;
file = fopen(argv[1], "r");
if(file != NULL)
{
while( fgets(line, sizeof line,file) != NULL)
{
strcpy(copy,line);
line_count++;
pch = strtok (line, " ");
while(pch != NULL)
{
if( strcmp(pch, test) == 0)
{
printf("\n%d:%s\n", line_count, copy);
}
pch=strtok(NULL, " ");
}
}
}
else{printf("\n\n\tError\n");}
return 0;
}//end main
Here is the text file I have been using to test the code. (It's an quote for the Godfather!)
Code:
I raised my daughter in the American
fashion; I gave her freedom, but
taught her never to dishonor her
family. She found a boy friend,
not an Italian. She went to the
movies with him, stayed out late.
Two months ago he took her for a
drive, with another boy friend.
They made her drink whiskey and
then they tried to take advantage
of her. She resisted; she kept her
honor. So they beat her like an
animal. When I went to the hospital
her nose was broken, her jaw was
shattered and held together by
wire, and she could not even weep
because of the pain.
Thanks!