C++ Binary Writing/Reading on 32bit to/from 64bit

Viewed 4865

If you have a binary output stream, and write integers to a file on a 32-bit Windows computer. Would you then be able to read the same integers from that same file on a 64-bit Windows computer?

My guess would be no. Since an integer on a 32-bit computer is 4 bytes, where an integer on a 64-bit computer is 8 bytes.

So does the following code work, while the files have to be able to be read and written from and by both 64-bit and 32-bit computers, no matter the OS, computer architecture and data type. If not how would one be able to do that, while the files have to be in binary form.

Writing

std::ofstream ofs("example.bin", std::ios::binary);

int i = 128;
ofs.write((char*) (&i), sizeof(i));

ofs.close();

Reading

std::ifstream ifs("example.bin", std::ios::binary);

int i = 0;
ifs.read((char*) (&i), sizeof(i));

ifs.close();
2 Answers
Related