ChikChak
ChikChak

Reputation: 1024

Writing/Reading from a file into struct in a struct

Lets say I have the following struct:

typedef struct s1 {
    int field1;
    int field2;
    struct s2 otherStruct; 
};

Where s2 is some other struct that I made:

typedef struct s2 {
    double field1;
    char unit;
};

If I use

s1 s;

s.field1 = 1;
s.field2 = 2;
s.otherStruct.field1 = 42;
s.otherStruct.unit = '!';

write(file_descriptor, &s, sizeof(s));

And then later:

read(file_descriptor, &s, sizeof(s));

Will it work? I mean, when I try to write s to the file, will it write all the fields of s correctly? Also, will it read it all back in correctly?

Upvotes: 0

Views: 89

Answers (1)

Jeffrey Rennie
Jeffrey Rennie

Reputation: 3443

This will work, if you compile the code with the same compiler, the same compiler flags, and run it on the same machine, and never change the definition of the structs. Change anything, and it you'll read garbage.

To solve this problem in a more resilient and portable way, consider Google's protobufs or Cap'n proto.

Upvotes: 2

Related Questions