BlogsDope image BlogsDope

Program to find and replace a word in a file by another word

Feb. 14, 2021 C C++ FILE 11097

Today we are going to talk  about a question you may face when dealing with files. Files are used to store data in a storage device permanently, suppose you misspelled a word and want to change it, you can't write the whole data again, you will try to find the word and then replace it with the correct word to get the work done. This is what we are going to deal with today. We will find and replace a string in a file by another string.

We are assuming you are familiar with file handling operations like opening a file, closing a file. And different modes of doing it, but if you are not or you want to go though it once you can visit here (File Handling).

Approach 

  1. We fill first ask the user to give the word(string) they want to replace and the word they want to replace it with.
  2. After the first step we will open two files, one file to read the data from, and another temporary file to store the output. (You can also use the first file to store the output, by taking the full string and again opening it in trunc mode and then output everything inside the file.)
  3. We will fetch every word using the  extraction operator (>>) from the file and compare it with the replacement word provided. If we find the word we will replace it.
  4. Lastly, close both the files.

Note

We have already created two files, codesdope.txt with text in it and an empty file temp.txt for storing the output.

Code to replace word in a file: 

//C++ Code
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    string replaceStr = "PAID"; //String to replace
    string replacementStr = "FREE";	//String To replace with
    ifstream filein("codesdope.txt"); //File to read from
    ofstream fileout("temp.txt"); //Temporary file
    string strTemp;

 while(filein >> strTemp)//taking every word and comparing with replaceStr
    {
        if(strTemp == replaceStr)//if your word found then replace
        {
            strTemp = replacementStr;
        }
        strTemp += " ";
        fileout << strTemp;//output everything to fileout(temp.txt)
    }
    filein.close();
    fileout.close();
    return 0;
}

Output -> After compiling the program, you can check you temp.txt file for results. The word PAID got replaced with the word FREE.​

file with correct text

Note to keep in mind :
 1. Include the iostream header file in the program to use its functions.
 2. Include the fstream header file in the program to use its classes.
 3. Apply the close() function on the object to close the file.


Liked the post?
Hi, I am Priyansh Jha. I am a pre-final year student of Electronics and Communication major undergraduate.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).