The closest equivalent is almost certainly to use istream::read
:
struct A {
char data[4];
int num;
};
A a;
std::ifstream in("somefile", std::ios::binary);
in.read((char *)&a, sizeof(a));
Note that this is equivalent to read
in a number of ways you'd probably prefer it wasn't--for example, it'll probably break if you upgrade your compiler, and might break just from breathing a little wrong.
If you insist on doing it anyway, you probably at least want to hide the ugliness a little:
struct A {
char data[4];
int num;
friend std::istream &operator>>(std::istream &is, A &a) {
return is.read((char *)a, sizeof(a));
}
};
Then other code will read an instance from a file with a normal insertion operator:
std::ofstream in("whatever", std::ios:;binary);
A a;
in >> a;
This way, when you come to your senses and serialize your object a little more sanely, you'll only need to modify operator>>
, and the rest of the code will remain unchanged.
friend std::istream &operator>>(std::istream &is, A &a) {
// At least deals with some of the padding problems, but not endianess, etc.
os.read(&a.data, sizeof(a.data));
return os.read((char *)&a.num, sizeof(a.num));
}
Then the rest of the code that uses this doesn't need to change:
A a;
in >> a; // remains valid