Reputation: 47
In this program i want to change some value in the file.Now i am opening the file in append mode and moving my seekp pointer to my given location.But the problem is that it is writing data at the end of file not there where the seekp pointer is there.
#include<iostream>
#include<fstream>
using namespace std;
int main(){
//creates a file for testing purpose.
ofstream fout;
fout.open("test.txt");
fout<<1;
fout<<" ";
fout<<34;
fout<<" ";
fout<<-1;
fout<<" ";
fout<<-1;
fout.close();
//reads the data in the file
ifstream fin;
fin.open("test.txt");
fin.seekg(0,ios::beg);
fin.unsetf(ios::skipws);//for taking whitespaces
char sp;
int item;
fin>>item;
while(!fin.eof()){
cout<<item<<endl;
fin>>sp;//to store whitespaces so that fin can take next value
fin>>item;
}
cout<<item<<endl;
fin.close();
//opening file for editing
fout.open("test.txt",ios::app);
fout.seekp(5,ios::beg);
fout<<3;
fout.close();
return 0;
}
Upvotes: 1
Views: 885
Reputation: 409166
If you read e.g. this reference you will see that std::ios::app
means
seek to the end of stream before each write
So it doesn't matter where you seek, all writes will be done at the end of the file.
The best way to modify a file is to read it into memory, then rewrite it to a temporary file, and then move the temporary file over the original file.
Upvotes: 2