Writing data structures using fstream write()

This won't compile:
1
2
3
4
5
6
7
8
9
10
11
12
struct s
{
char anything;
};

int main()
{
s st;
fstream file("x.txt");
file.write(st,sizeof(st)); //this won't compile
file.close();
}

My question is, how can i write data structs using fstream?
You have to cast into a char* which is guaranteed to work if and only if the struct is a POD type.

file.write(reinterpret_cast<const char*>(&st),sizeof(st));
Last edited on
You shouldn't do that...
Yes, do not just copy the bitpatterns of a structure to file. You should explicitly convert the object to some file storage. Google around "object serialization" for more.
Topic archived. No new replies allowed.