The description of the problem
I was ready to replace some data in a file and I also hope the original content has been conserved.
The first try and its failures
The codes
#include <iostream>
#include <fstream>
int main()
{
// test std::ios::ate
std::ofstream ofs("test.txt");
ofs << "Hello, World!" << std::endl;
ofs << "Hello, World!" << std::endl;
ofs.close();
// write 'B' to replace the first character in the test.txt without erasing the content
std::ofstream ofs_2("test.txt", std::ios::binary);
ofs_2.seekp(0, std::ios::beg);
ofs_2.write("B", 1);
ofs_2.close();
return 0;
}
The corresponding results
It is easy to find that when you use another object of ofstream to open a file, it will clear all the original content.
The second try
I just found that when you add
std::ios::app
, the original content will be conserved.
However, the problem is the seekp() will be useless.
correlated codes
#include <iostream>
#include <fstream>
int main()
{
// test std::ios::ate
std::ofstream ofs("test.txt");
ofs << "Hello, World!" << std::endl;
ofs << "Hello, World!" << std::endl;
ofs.close();
// write 'B' to replace the first character in the test.txt without erasing the content
std::ofstream ofs_2("test.txt", std::ios::binary|std::ios::app);
ofs_2.seekp(0, std::ios::beg);
ofs_2.write("B", 1);
ofs_2.close();
return 0;
}
corresponding results
Hello, World!
Hello, World!
B
The final solution
just add read mode into your object attributes
The related codes
Bello, World!
Hello, World!
Good luck