Search for a Word in a Text File using C++
Posted by Samath
Last Updated: January 04, 2017
  530

This program will search a file for a word entered by the user, if the word is found the program will specify the position and the number of occurences.

#include <iostream> 
#include <fstream>  
using namespace std;

int main()
{
  int ocurrences = 0;
  char word[20]; 
  int array_size = 1024; 
	char * array = new char[array_size]; 
	int position = 0; 

  cout << "Enter word: ";
  cin.getline(word,19);
  int word_size = 0;
  for(int i = 0; word[i] != '\0'; i++)
  {
    word_size++;
  }
  
	ifstream fin("wordBank.txt"); 
  if(fin.is_open())
	{
    cout << "File Opened successfully!" << endl;
		while(!fin.eof() && position < array_size)
		{
			fin.get(array[position]); 
			position++;
		}
		array[position-1] = '\0';

		for(int i = 0; array[i] != '\0'; i++)
		{
			for(int j = 0; word[j] != '\0' && j < 20 ; j++)
      {
        if(array[i] != word[j])
        {
          break;
        }
        else
        {
          i++;
          if(word[j+1] == '\0')
          {
            cout << "Word Found in File at position " << (i-word_size) << endl;
            ocurrences++;
          }
        }
      }
		}
    cout << "Total occurences found : " << ocurrences << endl;
	}
	else 
	{
		cout << "File could not be opened." << endl;
	}
	return 0;
}