Question #38289

Write a program to perform SEARCH and REPLACE operation on a text file. For this, input the name of a text file from the user. Then input two characters and search for the first character in the file and replace it with the second character. Do it for all the occurances of the first character in the text file. (Use a temporary file for this purpose)
1

Expert's answer

2014-01-13T15:23:24-0500

Answer on Question#38289- Programming, C++

1. Write a program to perform SEARCH and REPLACE operation on a text file. For this, input the name of a text file from the user. Then input two characters and search for the first character in the file and replace it with the second character. Do it for all the occurrences of the first character in the text file. (Use a temporary file for this purpose)

Solution.

#include <iostream>
#include <fstream>
using namespace std;
//reading from a file
void fileDisplay(char* path)
{
    ifstream iFSTR;
    iFSTR.open(path);
    char buffer[80];
    if(iFSTR.is_open())
    {
        while (iFSTR.good())
        {
            iFSTR.getline(buffer,80,'\n');
            cout<<buffer<<"\n";
        }
        iFSTR.close();
    }
    else
    {
        cout<<"Error opening file\n";
    }
}
//Replacing characters and write to the file
void changeToStars(char* path)
{
    long position;
    char ch;
    char firstSymb,secondSymb;
    cout<<endl<<endl<<"Enter first symbol: "<<endl; cin>>firstSymb;
    cout<<"Enter second symbol: "<<endl; cin>>secondSymb;
    fstream FSTR;
    FSTR.open(path,fstream::in | fstream::out);
    if(FSTR.is_open())
    {
        while(FSTR.good())
        {
            FSTR.get(ch);
            if(ch==firstSymb)
            {
                position = (long)FSTR.tellg();
                FSTR.seekp(position-1);
                FSTR<<secondSymb;
                break;
            }
        }
        FSTR.close();
    }
    else
    {
        cout<<"Error opening file\n";
    }
}
int main()
{
    char pathF[256];
    cout<<"File name: "<<endl; cin>>pathF;
    cout<<endl<<"Original file\n";
    cout<<"_________________________\n";
    fileDisplay(pathF);
    changeToStars(pathF);
    cout<<"\n\nChanged file\n";
    cout<<"_________________________\n";
    fileDisplay(pathF);
    cin>>pathF;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS