.
I've wrapped the functionality of this example into a simple class MyFile with Open, Read, write and Close member functions.
The Open Method
When fstream.open is called it requires several flags to indicate how the file will be used. This is similar to the "rb" "wb+" used in c files. There are several flags defined in ios_base - in, out, binary and trunc.
For random access we need in, out and binary. If ios_base::trunc is not ored in then the file must already exist or an exception is thrown. So to have it create a new file (or overwrite an existing) just or in ios_base::trunc.
The fstream.open() function requires a char * string (probably because it's just a wrapper round the C string file functions!) hence the use of the c_str() method to return a char * from a string. The Open function could fail, so check that it opened ok by calling the fstream.is_open() function.
Once the file is successfully open, strings can be written to file in a loop. Note that although these are binary files they are written sequentially, with each string padded to a width of RecLen (=10) with spaces. This uses a Try Catch just in case the disk fills up. It's a remote possibility but you'd feel silly if it happened.
Note:Another difference between binary and text files is that with binary files you can move through the file and read as well as write. With text files you are more or less (unless it's an unusual text file) forced to read it or write to it but not both.
On the next page : Random Access with Variable Length Records

