Reading struct from file?

Help please ! I have my settings stored in a struct(), and can manipulate them all normally. The save function to write them out to a file - all works ok -- BUT -- I'm not sure how to read them back into the struct as a single data block from the file

typedef struct MY_STRUCT { unsigned int THING1; byte THING2; byte THING3; }; // -------------------------------------------------- MY_STRUCT settings;... MY_STRUCT *pdPtr;

-- LATER--

// SAVE TO CFG FILE - WORKS OK File cfgFile =, FILE_WRITE); if (cfgFile.write((byte*) &settings, sizeof(settings))) { cfgFile.close();

-- AND --

// LOAD FROM CFG FILE - ??? File cfgFile =, FILE_READ); if (cfgFile) { char c; //?? pdPtr = &settings; while (c >= 0) { c =; //?? pdPtr++ = c; } cfgFile.close();

OK - you can see what I'm trying to do, but [u]what's the best way to READ that block[/u] of data back into the struct, without specifying individual .members ? It seems I'm close, but no prize - yet.


this might be usefull,

My favorite way is with a union. Set up a union with the struct and an array of bytes. Read the data off the file into the array of bytes and when you get to the end just use the struct form out of the union.

Something like:

typedef struct my_struct {
  unsigned int thing1;
  byte thing2;
  byte thing3;

union myUnion {
  my_struct asStruct;
  byte asBytes[4];

my_struct settings;

then to read it in you’d have something sort of like this: (assuming you’ve already created the file instance and all)

myUnion theUnion;
for( i=0; i<4; i++){
  byte b =;
  theUnion.asBytes[i] = b;
settings = theUnion.asStruct;

writing the struct out to the file would be similar:

myUnion theUnion;
theUnion.asStruct = settings;
for( i=0; i<4; i++){

SD has a stream read, can't you use that?

  int read(void *buf, uint16_t nbyte);

Something like:*) &settings, sizeof(settings));

(not tested)

Haha - too easy. [u]Exactly[/u] the reverse of my WRITE function - sigh.

Can't see the forest for the trees... Thanks for the stream read() hint...!

WRITE cfgFile.write((byte*) &settings, sizeof(settings))

READ*) &settings, sizeof(settings));

And the v1.0 code is 'done'! 1400 lines plus libraries.

Thanks - what an idiot I am!