write struct as raw data to file

Ali Çehreli acehreli at yahoo.com
Sun Sep 26 15:53:30 UTC 2021


rawRead and rawWrite work with slices (arrays) of things. You need to 
use an array of your struct even if there is a single item. Here is an 
example:

import std.stdio;
import std.file;

struct S {
   int i;
   double d;
}

void readFrom(string name) {
   // We need an array Ses (length of 1 in this case)
   auto ses = new S[1];

   File(name, "r").rawRead(ses);

   // Here is the first item of those ses:
   writefln!"Just read: %s"(ses[0]);
}

void writeTo(string name) {
   // Note the array of S passed to rawWrite
   File(name, "w").rawWrite([S(42, 1.5)]);
}

void main() {
   enum name = "rawWrite_struct_test";

   if (name.exists) {
     readFrom(name);
   }

   writeTo(name);
}

The program will create a file when you run it the first time and then 
it will also read from the that file on subsequent runs.

Ali



More information about the Digitalmars-d-learn mailing list