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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With