Reputation: 203
I have
fstream output;
output.open(fname, ios::out | ios::trunc); //file
for (int i=0; i<flength; i++)
output.put('1');
I want to overwrite different length of data to different locations in the file. Data is characters.
Lets say there is 111111111111111111111111111111111
, I want to write
11 111111333111!!!!!!1 11441111
Upvotes: 2
Views: 22318
Reputation: 73
The Best way is to rewrite the whole file into another file after making required changes.
std::ifstream fin("yourfile.txt");
remove("yourfile.txt");
Copy the stream before removing your file. This can help you preserve the name of the file.
Upvotes: 0
Reputation: 17169
You can't "insert" things in the middle of the file - the only inplace operations you can do is writing the exact same amount of bytes that you are trying to overwrite, i.e. writing without changing the length of the file. If you need to write a string of different length (as in your example) you have to rewrite the whole file from the point where you ended your write operation (store original in a buffer and rewrite).
Upvotes: 2
Reputation: 55705
You can use seekp to set the position of the put pointer and write at the specific position in the file, e.g.
output.seekp(10);
output.put('!');
Upvotes: 3