Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Beginner: How to search for particular words in a file (line by line) in C

I need to search for two particular words in a file line by line and if they exist, print "Found!".

This is file.txt (has four columns)

bill gates 62bill microsoft 
beyonce knowles 300mill entertainment 
my name -$9000 student

The following is the idea I had but it doesn't seem to work

char firstname[];
char lastname[];
char string_0[256];

file = fopen("file.txt","r+");

while((fgets(string_0,256,file)) != NULL) {

  //scans the line then sets 1st and 2nd word to those variables
  fscanf(file,"%s %s",&firstname, &lastname);

  if(strcmp(firstname,"beyonce")==0 && strcmp(lastname,"knowles")==0){
    printf("A match has been found");
  }
}

fclose(file);

Please help. Could it be that the pointer is not moving to the next line in the while loop? And if so, how can i fix?

like image 684
xWAV92OdD445CbzcZAEyunk2M06fJi Avatar asked Apr 20 '12 03:04

xWAV92OdD445CbzcZAEyunk2M06fJi


1 Answers

Instead of calling fscanf on the file after you've already read from it with fgets, you should be calling sscanf on the string_0 variable that you are copying the data to in your fgets call.

like image 161
Thomas Dignan Avatar answered Sep 30 '22 00:09

Thomas Dignan