Writing data to random access file


If a random access file is 3000 byte and i use the ostream seekp function to place the file position pointer at the 500th byte and then use ostream write function to write 50 bytes worth of data to the file.

Does the ORIGINAL data from the 500th to 549th bytes gets overwritten or will it be push_back to 550th to 599th byte and the file will expand to 3050 bytes in size?
The bytes in the range you specify will be overwritten.
With standard file system API's you can not "insert" or "cut out" bytes somewhere in the middle of a file.

At least not directly ;-)

You can append data to the end of the file, or truncate the end of the file (or overwrite existing data).

Consequently, in order to insert n bytes at position offset of a file, the files needs to be grown by n bytes and then all existing data ranging from position offset to the end of the file needs to be "moved" by n positions towards the end of the file - usually by copying that data in a block-by-block fashion (in back to front direction). Finally, the positions from offset to offset+(n-1) can be overwritten with the new data...

https://i.imgur.com/KyYPFvm.png
Last edited on
i figured out to expand the file i have to use ios::app.
thanks for the help.
but you still can't insert in the middle of a file without first moving the following towards the end of the file. See kigar64551 above.
do you have a problem in mind? your example file is so small its probably best to just read the whole thing into memory, abuse it there, and overwrite it back out when done. For larger files, you need to be smarter (it varies from system to system but these days 10s if not 100s of MB before you worry about it much).
Last edited on
Yes - I'd just read the whole file into a std::string, manipulate as required and then write the whole string back to the file. Easy, peasy...

Topic archived. No new replies allowed.