The next version of the Rolodex database program adds an index file to speed access to the rolodex records stored in the data file. As before, we focus on demonstrating the C++ stream member functions that enable the described functionality rather than on producing product-ready code. As such, we'll rely on a binary search, implemented with library functions, to look up the keys in the index file. The final version of the Rolodex program consists of five files:
card.h
Unmodified from the rolodexdb version 1 example: the
card
class specification and member functions.
key.h
The key class specification and inline member functions.
rolodex.h
The rolodex class specification and member function prototypes.
rolodex.cpp
Contains the rolodex class member function definitions.
rolodexdb.cpp
Unmodified from the rolodexdb version 1 example: defines main and other application functions.
The following figures describe the main features of the Rolodex database program. The source code for the complete program is available at the bottom of the page.
Feature
Description
char name[NAME_SZ];
streampos pos;
Private member fields for the name and data record position fields.
key()
Constructor that builds an empty key.
key(char* n)
Constructor that builds a key with just the name field filled - used to create a key object for use with the bsearch library function.
key(char* n, streampos pos)
Constructor that build a completely filled key object for mapping a name to a position the data file.
streampos get_pos()
A getter function that returns the position value.
static void sort(key* keys, int count)
A function that sorts the keys alphabetically by name. The function is made static - i.e., a class function - because it operates on an array of key objects rather than on a single, target object.
friend int korder(const void* e1, const void* e2)
A function that alphabetically orders two key objects. The function's signature (i.e., the argument list and return type) cannot be changed because the function is used by two C library functions, qsort and bsearch, but the function must access private members of the key class. Making the function a friend of the key class solves the conflict.
key.h. Instances of the key class, stored in the index file, map names to rolodex records in the data file.
Feature
Description
fstream index;
fstream data;
Stream objects to access the index and data files; both are private data members.
rolodex();
Constructor that creates and opens the index and data files.
~rolodex() { index.close(); data.close(); }
Destructor that closes the index and data files.
void add(char* name, char* address, char* phone);
Adds a new card at the end of the data file: Figure 3.
void search(char* name);
Searches for name in the index file; if the name is found, prints the information from the data file: Figure 4.
void list();
Lists all entries in the data file in alphabetical order Figure 5.