Reputation: 133
I am learning how to write to/read from binary files, and I want my files to be readable for any machine that supports C++ 17. So I had an horrifying thought: what if read() and write() are affected by the endianness of the machine?
For exemple: I run this code on a big endian machine,
#include <iostream>
#include <fstream>
#include <cstdint>
int main() {
std::ofstream Output("Hey.txt", std::ofstream::out | std::ofstream::binary);
if (Output.is_open()) {
int16_t i = 42;
Output.write((const char*)&i, 2);
}
}
Then I pass Hey.txt to a small endian machine, then run this code on the machine,
#include <iostream>
#include <fstream>
#include <cstdint>
int main() {
std::ifstream Input("Hey.txt", std::ifstream::in | std::ifstream::binary);
if (Input.is_open()) {
int16_t i;
Input.read((char*)&i, 2);
std::cout << i << std::endl;
}
}
Will the program print 42? Or is fstream handling the endian difference? If not, is there a way to prevent endian issues?
Thanks for your attention.
Upvotes: 5
Views: 2153
Reputation: 182753
Two simple rules:
If you're going to write binary data to a file, document the file format.
When you write binary data to a file, make sure the bytes you are writing match the requirements of the file format.
If the file format says that there's a 16-bit integer in big-endian format, and you write code that reads or writes that, everything will work fine.
Don't use a cast like this (char*)&i
because then the bytes will hold whatever format the native system happens to use for 16-bit integers and that is not even guaranteed (by the C++ standard) to be stable across runs of the same code on the same system.
Upvotes: 4