1

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

Winkz
  • 329
  • 2
  • 5
  • 19

3 Answers3

4

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.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • Where to write it though? :) – Winkz Jan 17 '13 at 10:51
  • @Winkz In the test clause of an `if` statement! :) – user4815162342 Jan 17 '13 at 10:53
  • hmm im gd rusty atm.. like this { if(strstr(line, damage){ fputs ( line, stdout ); /* write the line */ } } – Winkz Jan 17 '13 at 10:59
  • @Winkz Compilation or run-time error? Please note that StackOverflow is not a helpdesk; if you have a specific problem, feel free to ask it in the form of a new question. Also, please remember to upvote good answers and accept the one that helped you solve your problem, if any. This gesture rewards the volunteers writing the answers. – user4815162342 Jan 17 '13 at 18:14
1

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

MvG
  • 57,380
  • 22
  • 148
  • 276
granquet
  • 266
  • 2
  • 6
1

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.

MvG
  • 57,380
  • 22
  • 148
  • 276