#include <fstream>
#include <cstdint>
#include <iostream>
class Ofstream : public std::ofstream
{
public:
Ofstream(const std::string& s) : std::ofstream(s) {};
// for little-endian machines
Ofstream& put(int16_t val)
{
std::cout << "I call myself\n";
char lsb, msb;
lsb = (char)val;
val >>= 8;
msb = (char)val;
this->std::ofstream::put(lsb) && this->std::ofstream::put(msb);
return *this;
}
~Ofstream() {}
};
int main()
{
int16_t val = 0x1234;
Ofstream ofile("test");
ofile.put(val);
}
3. You ask why LOOPING occur. Because compiler make IMPLICIT CONVERSATION from char to int16_t in this line of code and again call YOUR put(int16_t) function:
put(lsb) && put(msb);
If you want to see this make overloading put(char c) function and you will see that it give error because it stop implicit conversation from char to int16_t.
Now I realized that I barked up the wrong tree. Because I want to use the binary numbers only at my system in main storage, I realized that the byte order for storing is irrelevant as long as the loading will handle this processing in reverse order.
So I have decided to abandon deriving from fstream and using rather the solution which @dutch presented.
I realized that the byte order for storing is irrelevant as long as the loading will handle this processing in reverse order.
As long as you're reading and writing on machines with the same endian-ness, this won't be a problem. Otherwise, you're better off seeing if your systems supports ntohl(), htonl(), ntohs() and htons(). These functions convert long (32 bit) and short (16 bit) values from network byte ordering (big endian) to host byte ordering and vice versa. So to write a 16 bit value you'd do
1 2
val = htons(val);
cout.write((constchar *)&val, sizeof(val));
and to read it:
1 2
cin.read((char *)&val, sizeof(val));
val = ntohs(val);
These functions are extremely efficient. x86 systems can do the byte swap in a single instruction and obviously for big-endian systems, the functions are nops.