CSV Data to Binary File

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 7 10:06:34 PDT 2014


On Thursday, 7 August 2014 at 16:08:01 UTC, TJB wrote:
> Thanks Marc. Not sure what to do here. I need to the binary 
> data to be exactly the number of bytes as specified by the 
> struct.
>
> How to handle the conversion from string to char[]?

Well, in your CSV data, they don't have the right length, so you 
have to decide how to handle that. The easiest way would be to 
set the length. This will fill up the string with "\0" bytes if 
it is to short:

align(1) struct QuotesBin
{
   int qtim;
   int bid;
   int ofr;
   int bidsiz;
   int ofrsiz;
   short mode;
   char[1] ex;
   char[4] mmid;

   this(const QuotesBinDummy rhs) {
     this.qtim = rhs.qtim;
     this.bid = rhs.bid;
     this.ofr = rhs.ofr;
     this.bidsiz = rhs.bidsiz;
     this.ofrsiz = rhs.ofrsiz;
     this.mode = rhs.mode;
     string tmp;
     tmp = rhs.ex;
     tmp.length = this.ex.length;
     this.ex = tmp;
     tmp = rhs.mmid;
     tmp.length = this.mmid.length;
     this.mmid = tmp;
   }
}

...
     auto temp = csvReader!QuotesBinDummy(line).front;
     QuotesBin record = temp;
     fout.writeExact(&record, QuotesBin.sizeof);
...

But of course, whether this is correct depends on whether your 
binary format allows it, or requires all chars to be non-zero 
ASCII values.


More information about the Digitalmars-d-learn mailing list