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;
}
Comments