1. Technology
Send to a Friend via Email

C++ Programming Tutorial - C++ Strings

By

7 of 9

More on Example 2
The GetRecordCount() Function. It's useful knowing how many records there are so this function moves the read file pointer to the end of the file with seekg, then divides the size of the file (in bytes) by reclen. Both seekg and seekp (g is for get, ie read and p is for put ie write) use the constants ios_base::beg, ios_base::end and ios::cur. These correspond to the fseek constants SEEK_SET etc in C. ios_base::beg means seek relative to the start of the file, ios_base::end mean seek relative to the end of the file and ios_base::cur means move relative to the current file position.

Having written the files, it's useful to test that we can directly retrieve any specified record from the data file. After opening it for reading, the MyFIle::Read() function seeks to the appropriate point ( index * RecLen ) then reads RecLen bytes.

Example 3

Instead of using a single file with fixed length records we use two files; one holding an index and one holding data in variable length records. The index record (a struct called indextype) consists of two int fields: a position and a size. All the indexes are held in data.idx and the main data in data.dat. Because each record can vary in size, we can't do a simple multiply to work out where it starts and so we need a position value to say where a given record starts and a size to indicate how long it is.

As with example 2, I've wrapped an fstream object in the class MyFile. I've also (for the first time in any tutorial) used an STL class vector to hold a variable size array of indextype structs and use a class char * buffer to hold data temporarily.

On the next page : Random Access with Variable Length Records

©2014 About.com. All rights reserved.