As commented on answer from AwaitedOne I dislike writing a lot of code for every single output statement. Instead I prefer having a overload for shift operator to make user code a bit easier and less error prone.
As a startpoint the following example is given. There are not all possible overloads presented and also the BinaryFile class is less then "ready for production". It is only given as a compileable startpoint to start own investigations.
Keep in mind:
binary file is not portable, binary representation can change from version to version of compiler/libc/other. It is also dependend of OS and endianess of system and also of the architecture ( 32 vs 64 bit ) and many others.
So binary data should not be used in general to make data persistent for "later" use unless you write handler methods, which have a defined in/out format. My example write simple the memory of the storage of the data which is very stupied and results in all the problems are mentioned. Feel free to start an own "perfect" implementation for an exchangeable binary format.
But instead of reinvent the whell, someone should use ready to use implementations given already everywhere. Search for "serializer" and you will find a good set of libs like boost serialize and many others.
#include <fstream>
#include <cstring>
class BinaryOut: public std::ofstream
{
public:
BinaryOut( const char* fname ):
std::ofstream( fname, std::ios::binary )
{}
};
// use a generic func to use for everything which not handled in special way
template < typename DataType >
BinaryOut& operator << ( BinaryOut& out, const DataType& data )
{
out.write( (char*)&data, sizeof( DataType ));
return out;
}
// if pointer type, write not pointer but values which pointer points to:
template < typename DataType >
BinaryOut& operator << ( BinaryOut& out, const DataType*& data )
{
out.write( (char*)data, sizeof( DataType ));
return out;
}
// special case for char ptr ( old style c string ) which ends with '\0'
// use old style c here ( no std::string is involved )
BinaryOut& operator << ( BinaryOut& out, const char* ptr )
{
out.write( ptr, strlen( ptr ));
return out;
}
// may be some more overloads for << if needed...
int main()
{
BinaryOut out("example.bin");
int i=123;
double d=9.876;
double* ptrd=&d;
const char* dummy = "Ptr to Text";
out << i << d << ptrd << "Hallo, this is a test" << dummy;
}