Reputation: 161
I know what this code does: copies the content from the memory pointed by &x into the file, for sizeof(double) bytes; reads the file and copies into the memory pointed by &y, for sizeof(double) bytes.
double x,y;
std::ofstream out( "abc.dat", std::ios::out | std::ios::binary);
out.write( reinterpret_cast<const char*>(&x), sizeof(double));
out.close();
std::ifstream in( "abc.dat", std::ios::in | std::ios::binary);
in.read( reinterpret_cast<char*>(&y), sizeof(double));
in.close();
From what I understand, when doing binary IO, the data flowing between the file and RAM should be in terms of bytes. Then the &x address should be passed as a byte location: something like out.write( reinterpret_cast< const byte*>(&x), sizeof(double)) would make sense. However C++ does not define a type byte, and here the char* can be understood as a byte location, am I right? I note that the size of char is identical as one byte, they are both 8 bits.
Upvotes: 1
Views: 137
Reputation: 2520
Yes the size of char is 1 byte in c++.
Other than that sizes are a little more fluid. Which is why some vendors offer non-standard extensions which guarantee sizes. For instance in Microsoft VC there is the WORD which is 16 bits.
Check out this page for more info: http://en.cppreference.com/w/cpp/language/types
Upvotes: 2