Reading a string in binary mode

Ali Çehreli acehreli at yahoo.com
Mon Mar 3 14:06:38 PST 2014


On 03/03/2014 01:44 PM, 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?

You need to have a buffer of 'size'. Not tested:

     auto s = new char[size];
     s = _f.rawRead(s);
     x = s;

However, the last line will not compile due to difference in mutability. 
So will need to do something like this:

     import std.exception : assumeUnique;

     x = assumeUnique(s);

 >          }
 >      }
 >
 > Writing is ok, but how do I read the bytes to the
 > string x after having its size?

Ali



More information about the Digitalmars-d-learn mailing list