What Random Access Can Do
After opening an existing file, we can position a file pointer (two actually, one for read and one for write) anywhere within the file, including the end of it and write data to it or read from it. It's a good idea if you're reading from the file to always check the ios::eof flag. This tells you if you are trying to read from the end of the file.There is complete freedom to read or write any data anywhere with random access. Here are a couple of examples why you might do this.
- Serialization. This is a common technique for taking aggregated data (ie struct or class) and writing the data to a stream. At it's simplest it might mean having a method that writes all of the member data to a stream as strings. If those member data elements are also instances of a class then they have to be serialized and it can get complicated. Also you need a corresponding unserialize method that can read from
a stream and populate the member data. This is sometimes implemented as an overloaded constructor.
- Persisting data to disk. This can be done with fixed length blocks. Imagine a file of chess board positions, each 64 bytes long representing a chess board.
On the next page : An Example of Random Access Strings

