Hi guys,

I'm trying to make a program where i read in two words and then search a text file for each occurence of that word. Also I want to print the first line that each word occurs in.
My problem is after i get into the file I cannot find a way to find a matching word AND print the first line it occurs in.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

FILE *infile;
int main() {
	int i, j, k, result;
	char word1[20], word2[50], line[120], word[120], current[50];
	int length;
	
	printf("Enter the first word to search for: ");
	gets(word1);
	printf("Enter the second word to search for: ");
	gets(word2);
	infile = fopen("Fruits.txt","r");
	if(infile == NULL) {
		printf("ERROR: Cannot open Fruits.txt");
		exit(21);
	}
	
	i=0;
	while(fgets(line,500,infile)!=NULL){
        

         /*Need to check for word1 and word2 if they occur in Fruits.txt, and also print the first line at which they are found.*/



	fclose(infile);
}

Edited 6 Years Ago by WaltP: Use CODE tags!!

Include string.h header file, and use strstr() to check each line of text, in the char array "line".

For each line, you may need to have two checks, one for each word, depending on the specifics of your search.

If the words are found, print the line array. Note that strstr() returns a pointer, and that pointer will have the address of the found word (if it's there), or NULL otherwise.

Carry on!

One way is after you read the line, read each word of the line within a loop using sscanf() .

This article has been dead for over six months. Start a new discussion instead.