Reputation: 329
HI guys havent been able to find how to search for specific words in a text file anywhere, so here it goes, this is what I have now and just read and prints the entire text file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ( void )
{
static const char filename[] = "chat.log";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
Thank you :D
Upvotes: 1
Views: 11062
Reputation: 60988
When searching for a fixed set of words, I suggest you have a look at the Aho-Corasick algorithm. It's really good in terms of performance.
Upvotes: 1
Reputation: 286
your approach would work but it's a bit naive and you could do far better than that.
here's an excellent algorithm for string searching: Boyer–Moore string search algorithm
Upvotes: 1
Reputation: 155296
Use strstr(line, word)
to look for the word anywhere inside the line. If strstr
returns non-NULL, it means the current line contains your word.
Upvotes: 4