Example
The following example shows the use of class
RWFileManager to construct a linked-list of
int s on disk. The source code is included in the
buildspace\examples\tools directory as
fmgrsave.cpp and
fmgrrtrv.cpp. When using this example, you must type a carriage return after the last item you want to insert in order to guarantee that it will be added to the list. This is because different compilers handle the occurrence of an EOF on the
cin stream differently.
#include <rw/filemgr.h> // 1
#include <rw/rstream.h>
struct DiskNode { // 2
int data; // 3
Rwoffset nextNode; // 4
};
int main(){
RWFileManager fm("linklist.dat"); // 5
// Allocate space for offset to start of the linked list:
fm.allocate(sizeof(RWoffset)); // 6
// Allocate space for the first link:
RWoffset thisNode = fm.allocate(sizeof(DiskNode)); // 7
fm.SeekTo(fm.start()); // 8
fm.Write(thisNode); // 9
DiskNode n;
int temp;
RWoffset lastNode;
std::cout << "Input a series of integers, ";
std::cout << "then EOF to end:\n";
while (std::cin >> temp) { // 10
n.data = temp;
n.nextNode = fm.allocate(sizeof(DiskNode)); // 11
fm.SeekTo(thisNode); // 12
fm.Write(n.data); // 13
fm.Write(n.nextNode);
lastNode = thisNode; // 14
thisNode = n.nextNode;
}
fm.deallocate(n.nextNode); // 15
n.nextNode = RWNIL; // 16
fm.SeekTo(lastNode);
fm.Write(n.data);
fm.Write(n.nextNode);
return 0;
} // 17
Here is a line-by-line description of the program:
Having created the linked-list on disk, how might you read it? Here is a program that reads the list and prints the stored integer field:
#include <rw/filemgr.h>
#include <rw/rstream.h>
struct DiskNode {
int data;
RWoffset nextNode;
};
int main(){
RWFileManager fm("linklist.dat"); // 1
fm.SeekTo(fm.start()); // 2
RWoffset next;
fm.Read(next); // 3
DiskNode n;
while (next != RWNIL) { // 4
fm.SeekTo(next); // 5
fm.Read(n.data); // 6
fm.Read(n.nextNode);
std::cout << n.data << "\n"; // 7
next = n.nextNode; // 8
}
return 0;
} // 9
And this is a line-by-line description of the program: