C++ Remove All the Occurrences of a Word From File
Posted by Samath
Last Updated: January 05, 2017

This program basically accept a word from a user and search a file and remove all the Occurrences of that word from the file.

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

int main()
{
  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())
	{
		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')
          {
            for(int k = (i-word_size); array[k] != '\0'; k++)
            {
              array[k] = array[k+word_size];
            }
            i = i - (word_size+1); 
          }
        }
      }
		}
    fin.close();
    ofstream fout("WordBank.txt");
    for(int i = 0; array[i] != '\0'; i++)
    {
      fout << array[i];
    }
    cout << "Words removed..." << endl;
	}
	else 
	{
		cout << "File could not be opened." << endl;
	}
	return 0;
}