Reading a string in binary mode
John Colvin
john.loughran.colvin at gmail.com
Mon Mar 3 14:08:33 PST 2014
On Monday, 3 March 2014 at 21:44:16 UTC, Christof Schardt wrote:
> I'm evaluating D and try to write a binary io class.
> I got stuck with strings:
>
> void rw(ref string x)
> {
> if(_isWriting)
> {
> int size = x.length;
> _f.rawWrite((&size)[0..1]);
> _f.rawWrite(x);
> }
> else
> {
> int size;
> _f.rawRead((&size)[0..1]);
>
> ... what now?
> }
> }
>
> Writing is ok, but how do I read the bytes to the
> string x after having its size?
Assuming you're not expecting pre-allocation (which I infer from
your choice of "ref string" instead of "char[]"), you could do
this:
> void rw(ref string x)
> {
> if(_isWriting)
> {
> size_t size = x.length;
> _f.rawWrite((&size)[0..1]);
> _f.rawWrite(x);
> }
> else
> {
> size_t size;
> _f.rawRead((&size)[0..1]);
> auto tmp = new char[size];
> _f.rawRead(tmp);
> import std.exception : assumeUnique;
> x = tmp.assumeUnique;
> }
> }
More information about the Digitalmars-d-learn
mailing list