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
Check out
ostream::seekp
, here. Position the file-pointer to the desired location before writing.You can use seekp to set the position of the put pointer and write at the specific position in the file, e.g.
Use
seekp()
to set the writing position in the file stream.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).
The Best way is to rewrite the whole file into another file after making required changes.
Copy the stream before removing your file. This can help you preserve the name of the file.