I was trying to replace a string in a text file. Something like replace() function.
Here is the code:
#include <iostream>
#include <fstream>
#include <cstring>
Using namespace std;
int main()
{
fstream file("C:\\Users\\amir hossein\\Desktop\\Temp1\\test1.txt");
char *sub; sub = new char[20]; sub = "amir";
char *replace1; replace1 = new char[20]; replace1 = "reza";
char *buffer; buffer = new char[100];
int i, temp; streampos flag;
int c=0,mark;
bool flagforwrite=0;
if (file.is_open()){
while (!file.eof()) {
flag = file.tellg();
file.getline(buffer, 100); //We'll Search Sub inside of Buffer, if true, we'll replace it with Replace string
flagforwrite=0;
for (i=0;buffer[i];i++){
mark=i; c=0;
while (sub[c] && sub[c]== buffer[mark]){
c++; mark++;
}
if (!sub[c]){ //Make Changes in The Line
for (int j=i,count=0;count<strlen(replace1);j++,count++) buffer[j] = replace1[count]; //until here, we've replace1d the sub
flagforwrite=1;
}
}
if (flagforwrite){ //Write The line ( After Whole Changes In line have been made!!
file.seekp(flag);
file << buffer << "\n"; // ENDL here IS SUPER IMPORTANT!! IF you don't put it, I'll mess it up
if(file.bad()) cout << "Error\n";
}
}
}
else cout << "Error!!\n";
file.close();
delete[] sub;
delete[] replace1;
delete[] buffer;
return 0;
}
I want to replace "amir" with "reza".
My text file includes 4 lines:
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
When I run the program I get this.
Hi My name is reza and also my friend's name is reza too!
Hi My name is reza and also my friend's name is reza too!
Hi My name is reza and also my friend's name is reza too!
Hi My name is amir and also my friend's name is amir too!
What is wrong with the last line?
I think that problem is here:
if (flagforwrite){
file.seekp(flag);
file << buffer << "\n";
if(file.bad()) cout << "Error\n";
}
Why is the flag always referring to the line?
I'm using GNU GCC compiler.