1. Computing & Technology

Discuss in my forum

C++ Programming Tutorial - C++ Strings

By , About.com Guide

Random Access with variable Length Records
Download Example 3
.

The first part of the program creates the data file and generates an index in the indexvector. If you haven't seen a vector used before don't panic. This declaration below says that the variable indexvector holds a vector (a single dimension array) of indextype. It's type safe so no other data types can be held. It's also dynamic so we can add or delete elements at run-time. A vector is just a name for a single dimension array or list.

vector<indextype> indexvector;
This creates an empty vector. As with example 2, the MyFile::Open takes an optional parameter to specify if we are creating (or wiping an existing) file. It also calls ReadIndex which tries to load the contents of indexfile into the vector. While it would be easy enough to read each indextype struct as we need it, it's quicker to read them all into memory in one go. If the index file exists and can be opened, and there are records then the loop reads them in one by one and adds a copy of each on the end of the vector using
indexvector.push_back(irec)

As the data file is written in MyFile::Write, push_back which is also called to build up the index in memory. There are two cases here. The first is when the data file (and index) is being created and the second when the index exists and is read into memory.

The index in memory is saved to disk when the MyFile::Close method is called. If you forget this and the destructor is called, then if the file hasn't been closed then MyFile::Close gets called.

On the next page : Finishing Off

©2012 About.com. All rights reserved.

A part of The New York Times Company.