Writing Classes to File

BCS BCS_member at pathlink.com
Tue May 9 17:07:18 PDT 2006


In article <e3qg96$2vio$1 at digitaldaemon.com>, BCS says...
[...]
>I have a linked list example I can post if anyone is interested but it 
>will have to wait till Monday (I'm books until then).

Um, I'm not a busy as I thoght. Here it is.

works on linux (dmd ~v.153 I think)
may need some tweeking for win
make shure ./test is not an important file as it get trashed.
--------------------------
import std.stdio;
import std.stream;


int main(char[][] argv)
{
LLItem List1, List2;

// construct a linked list
List1 = new LLItem(argv, 0);

// open a file
Stream str = new File("./test", FileMode.OutNew);
long pos, first;

// store the "header"
pos = str.position;
str.writeExact(&first, long.sizeof);

// dump list
first = List1.DumpToFile(str);

// over write header
str.position = pos;
str.writeExact(&first, long.sizeof);

// re open file
str.close;
str = new File("./test",FileMode.In);

// read header
str.readExact(&first, long.sizeof);

// read list
str.position = first;
List2 = LLItem.ReadFromFile(str);

// print list
while(null !is List2)
{
writef("%d:%s\n", List2.integer, List2.string);
List2 = List2.next;
}

return 0;
}




class LLItem
{
char[] string;
int integer;
LLItem next;

private this(){}

// turn list of args into a linked list
this(char[][] args, int i)
{
string = args[0];
integer = i;
if(1 < args.length)
next = new LLItem(args[1..$], i+1);
}

static struct LLItemDump
{
int strLength;
long string;
int integer;
long next;
}

long DumpToFile(Stream outs)
{
LLItemDump dump;

// deal with int
dump.integer = integer;

// deal with next
if(null is next)
dump.next = 0;
else
dump.next = next.DumpToFile(outs);

// deal with string
dump.strLength = string.length;
dump.string = outs.position;
outs.writeExact(string.ptr, string.length);

// dump
long pos = outs.position;
outs.writeExact(&dump, LLItemDump.sizeof);

return pos;
}

static LLItem ReadFromFile(Stream ins)
{
//get item
LLItemDump dump;
ins.readExact(&dump, LLItemDump.sizeof);

LLItem ret = new LLItem;

//deal with int
ret.integer = dump.integer;

// deal with next
if(0 == dump.next)
ret.next = null;
else
{
ins.position = dump.next;
ret.next = LLItem.ReadFromFile(ins);
}

//deal with string
ret.string.length = dump.strLength;
ins.position = dump.string;
ins.readExact(ret.string.ptr, dump.strLength);

return ret;
}
}





More information about the Digitalmars-d mailing list