What it the preferred method to write a class to a file?
Charles D Hixson
charleshixsn at earthlink.net
Sun Jul 23 15:01:47 PDT 2006
Chad J wrote:
> Charles D Hixson wrote:
>>...class method).
>>
>> It this the best approach? Also are there any suggestions
>> as to a reasonable way to specify the type id, so that it
>> would be the same from run to run? Should I keep track of
>> the ids myself (manually)? If not, how would I know on an
>> attempt to read which class the type id referred to?
>
> There was a discussion about this a while ago that had some suggestions,
> at least for the binary approach:
> http://www.digitalmars.com/d/archives/digitalmars/D/37739.html
>
> Hope it helps.
Well, before I read it I had written (slightly trimmed):
const uint eor = 0x19191919;
class nnv
{ protected float[] vec;
const char[4] sig = "nvec";
ulong write(Stream s)
in
{ assert (s.isOpen());
assert (s.seekable);
}
body
{ ulong oStart = s.position;
s.write(cast(ulong)0);
s.write(sig[0]); s.write(sig[1]);
s.write(sig[2]); s.write(sig[3]);
s.write(cast(ulong)(this.vec.length));
foreach(float f; this.vec) s.write(f);
s.write(eor);
ulong oEnd = s.position;
s.position = oStart;
s.write(cast(ulong)(oEnd - oStart) );
s.position = oEnd;
}
}
So I guess that we're heading in the same directions (except
that for this class a separate struct didn't make much
sense). I should probably calculate the overhead so that I
don't need to go back and forth to write the length. I
return the position to make it easy to create an index, and
include length, type, and eor to make it feasible to rebuild
an index if the current one becomes corrupt. (Theoretically
I shouldn't need the eor...but I grew up with tape parity
errors, and anyway any compression method would reduce that.
The problems with this solution come in scaling. Consider
what would happen if one were dealing with many different
kinds of record...and some were composite. Do-able doesn't
mean elegant.
This basic design is limited in the number of kinds of
record it can handle...but long before that limit is reached
it would be paralyzed by the clumsiness.
P.S.: Is there a standard library routine for converting
between strings of length 4 and uint-s? If so I wasn't able
to find it. If not, I wasn't able to determine that it
didn't exist. (That would have made writing the sig more
efficient.)
More information about the Digitalmars-d-learn
mailing list