c++ - Writing on last line with fstream -
i trying replace string in text file. replace() function.
here 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 replace string flagforwrite=0; (i=0;buffer[i];i++){ mark=i; c=0; while (sub[c] && sub[c]== buffer[mark]){ c++; mark++; } if (!sub[c]){ //make changes in line (int j=i,count=0;count<strlen(replace1);j++,count++) buffer[j] = replace1[count]; //until here, we've replace1d sub flagforwrite=1; } } if (flagforwrite){ //write line ( after whole changes in line have been made!! file.seekp(flag); file << buffer << "\n"; // endl here super important!! if don't put it, i'll mess if(file.bad()) cout << "error\n"; } } } else cout << "error!!\n"; file.close(); delete[] sub; delete[] replace1; delete[] buffer; return 0; }
i want replace "amir" "reza".
my text file includes 4 lines:
hi name amir , friend's name amir too!
hi name amir , friend's name amir too!
hi name amir , friend's name amir too!
hi name amir , friend's name amir too!
when run program this.
hi name reza , friend's name reza too!
hi name reza , friend's name reza too!
hi name reza , friend's name reza too!
hi name amir , friend's name amir too!
what wrong last line?
i think problem here:
if (flagforwrite){ file.seekp(flag); file << buffer << "\n"; if(file.bad()) cout << "error\n"; }
why flag referring line?
i'm using gnu gcc compiler.
i found problem! caused eof()! instead of using while(!file.eof())
used while(file.getline(buffer,100))
and moved file.tellg() end, , defined line this: streampos line=file.tellg();
Comments
Post a Comment