#include <storage/memfile.h>
#include <string.h>
#include <iostream.h>

using namespace os;

char *txt = "Initializer string.\n"
	"This string is constant and will not be changed by the MemFile "
	"object.\nPlease note that the string must remain in memory as "
	"long as the MemFile object does! (Not copied until written to.)";

int main( void )
{
	// Allocate a MemFile on the stack, and initialize it to "txt".
	// (+1 is to get the NULL terminator.)
	MemFile		mf( txt, strlen(txt) + 1 );

	char		bfr[1024], *p;
	int		i;

	cout << "Trying to read 1024 bytes of data:" << endl;
	i = mf.ReadPos(0, bfr, sizeof(bfr));
	cout << "Got " << i << " bytes. Contents follow:" << endl;
	cout << bfr << endl << endl;

	mf.Seek( 0, SEEK_END );
	cout << "File size is now: " << mf.Seek( 0, SEEK_SET ) << endl;

	p = "Hello MemFile!";

	cout << "Writing string outside the initialized region...\n";
	mf.WritePos(1000, p, strlen(p) + 1);
	cout << "Reading back...\n";
	i = mf.ReadPos(1000, bfr, sizeof(bfr));
	cout << "Got " << i << " bytes. Contents follow:" << endl;
	cout << bfr << endl << endl;

	mf.Seek( 0, SEEK_END );
	cout << "File size is now: " << mf.Seek( 0, SEEK_SET ) << endl;

	// The 'txt' string is still not copied, but writing in the
	// initialized reqion will force the MemFile to copy it.

	p = "Once the region that holds the initial string is written to, "
	    "it will be copied to allow for writing, not affecting the "
	    "original string.";

	cout << "Writing string across block boundaries...\n";
	mf.WritePos(strlen(txt) - 30, p, strlen(p) + 1);
	cout << "Reading back...\n";
	i = mf.ReadPos(strlen(txt) - 30, bfr, sizeof(bfr));
	cout << "Got " << i << " bytes. Contents follow:" << endl;
	cout << bfr << endl << endl;

	cout << "Trying to read 1024 bytes of data:" << endl;
	i = mf.ReadPos(0, bfr, sizeof(bfr));
	cout << "Got " << i << " bytes. Contents follow:" << endl;
	cout << bfr << endl << endl;

	mf.Seek( 0, SEEK_END );
	cout << "File size is now: " << mf.Seek( 0, SEEK_SET ) << endl;

	cout << "Sequential read (all non-NULL characters to the end of the file): " << endl;
	i = 0;
	while( mf.Read( bfr, 1 ) == 1 ) {
		if(bfr[0]) cout << bfr[0];
	}
	cout << endl;

	return 0;
}


























